也许我错过了一些东西。我无法找到Observable及其语法的简单教程。我正在使用Angular,我需要从服务中调用一个函数(在一个组件中定义)。我读了solution。但我无法弄清楚如何改变服务中创建的Observable的值(也许创建不是最好的方法)。Typescript Angular - Observable:如何更改其值?
我有一个成分像的解决方案:
@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??
}
}
我无法准确提取您想要执行的操作。你能否给你的问题多一些背景?为什么你(想)你想从一个服务调用一个组件功能? Observable就像是一种承诺:通常用在Component中,当某个异步操作完成时,要求Service返回一个Observable,并在Component(或另一个Service)内部采取行动。 – msanford
您链接的其他问题与使用服务作为两个组件之间的中介相关。这是你想要做的吗? – msanford
'this.condition = Observable.of(false)'为你工作吗? – msanford