也許我錯過了一些東西。我無法找到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