[英]How to use Behaviour Subjects in Angular4
我正在使用一項服務來保存一個值並在另一組件中使用。 這是我的服務,
export class PageService {
template_type$:Observable<any>;
private myMethodSubject1 = new BehaviorSubject<any>('hi');
constructor() {
this.template_type$ = this.myMethodSubject1.asObservable();
}
template_type(selectedType){
this.myMethodSubject1.next(selectedType);
//console.log(selectedType);
}
}
在我的職責中,我向這項服務傳遞價值,
this.pService.template_type('one');
在同一個組件的另一個功能中,我稱此服務以獲取價值
this.pService.template_type$.subscribe(data=>{
console.log(data);
})
但是它首先返回“ hi”,在函數調用后返回值..但是我首先需要值...代碼中是否有錯誤?
聽起來您不想使用BehaviorSubject
,而是要使用ReplaySubject(1)
:
private myMethodSubject1 = new ReplaySubject<any>(1);
沒有初始值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.