我對Observables很新。我怎樣才能從一個簡單的字符串創建Observable?然後訂閱它並在更改時輸出它。從一個字符串(角2)可觀察到
這有道理嗎?
我沒有任何運氣與谷歌搜索。可能錯誤的關鍵字?
添加一些代碼更好的解釋:
My constructor on service
constructor() {
// Create observable stream to output our data
this.notice = Observable.create(
(observer) => this.observer = observer;
);
};
My method on service
set(string) {
this.notice.subscribe((value) => {
// Push the new value into the observable stream
this.observer.next(string);
}, (error) => console.log('Could not set data.'));
}
Calling service method
setNotice(event) {
event.preventDefault();
// Calling service to set notice
this.noticeService.set('This is a string');
}
我想我錯在這裏做什麼?但不知道如何問。我會很感激任何解釋。
waht關於this.notice.unsubscribe()在ngDestroy()呢?我知道這是手動添加事件偵聽器的內存泄漏的常見原因......所以我認爲這將是相同的。 – JGFMK
我也會爲此考慮BehaviorSubject。 https://stackoverflow.com/questions/39494058/behaviorsubject-vs-observable – JGFMK