也许我错过了什么.我找不到关于Observable及其语法的简单教程.我正在使用Angular,我需要从服务调用一个函数(在组件中定义).我读了solution页.但我不知道如何改变服务中创建的可观察值(也许创建不是最好的方法).

我在解决方案中有一个类似的组件:

@Component({
  selector: 'my-component',
  ...
)}
export class MyComponent {
   constructor(myService:MyService) {
   myService.condition.subscribe(value => doSomething(value));
}

doSomething(value) {
  if (value) // do stuff
  else // other stuff
}

}

这是我的服务:

import { Injectable } from '@angular/core';
import { Observable} from 'rxjs/Observable';

@Injectable()

export class MyService {
    private condition: Observable<boolean>;
    constructor() { 
       this.condition= new Observable(ob => {ob.next(false); })
       // maybe ob.next is not the best solution to assign the value?
    }

    change() {// how can i change the value of condition to 'true', to call
              // the doSomething function in the component?? 
    }

}

推荐答案

my other answer上的 comments (保留下来,因为它可能对某人有帮助),你似乎想利用某些东西的力量来释放over time.

正如多姆泽所提议的,使用一个主题,但这里有一个(微不足道的)例子,说明你可以这样做.虽然显然有some pitfalls to avoid in using Subject directly个,我还是让你决定吧.

import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { Observable, Subject } from 'rxjs/Rx';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Open the console.</h2>
    </div>
  `,
})
export class App {

  constructor() {}

  let subject = new Subject();

  // Subscribe in Component
  subject.subscribe(next => {
    console.log(next);
  });

  setInterval(() => {
    // Make your auth call and export this from Service
    subject.next(new Date())
  }, 1000)
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Plunker

以我的拙见,对于这种情况,我不明白为什么一个简单的服务/可观察性还不够,但这不关我的事.

进一步阅读:Angular 2 - Behavior Subject vs Observable?

Typescript相关问答推荐

错误:note_modules/@types/note/globals.d.ts:72:13 -错误TS 2403:后续变量声明必须具有相同的类型

使用新控制流的FormArray内部的Angular FormGroup

如何为ViewContainerRef加载的Angular组件实现CanDeactivate保护?

如果一个变量不是never类型,我如何创建编译器错误?

在NextJS中获得Spotify Oauth,但不工作'

打印脚本丢失函数的泛型上下文

无法绑定ngModel.条件ngSwitchCase中的错误

泛型类型联合将参数转换为Never

路由链接不会导航到指定router-outlet 的延迟加载模块

如果字符串文字类型是泛型类型,则用反引号将该类型括起来会中断

如何在TypeScrip中正确键入元素和事件目标?

参数属性类型定义的REACT-RUTER-DOM中的加载器属性错误

在VSCode中显示eslint错误,但在终端中运行eslint命令时不显示?(Vite,React,TypeScript)

TYPE FOR ARRAY,其中每个泛型元素是单独的键类型对,然后在该数组上循环

为什么&Quot;元素隐式具有';Any';类型,因为...即使我已经打字了,也不能作为索引显示错误吗?

使用Type脚本更新对象属性

Angular NG8001错误.组件只能在一个页面上工作,而不是在她的页面上工作

为什么TypeScrip假定{...省略类型,缺少类型,...选取类型,添加&>}为省略类型,缺少类型?

如何避免多个类型参数重复?

Typescript 子类继承的方法允许参数中未定义的键