![](/img/trans.png)
[英]RxJS Observable with Subject, polling via timer and combineLatest does not fire
[英]Does combineLatest not fire becuase of the behaviorSubject?
以下代碼來自我的服務組件。 它要求用戶可觀察,並且數據要在BehaviorSubject中提交。 我叫form.service.formToSubmit$.next(form);
更新它。 因為combinateLatest也在用戶可觀察到的發射時觸發,所以我檢查formToSubmit是否不為空,並且在提交后將其設置為null。 但是當我更新formToSubmit時它沒有觸發。 我已經嘗試過一切。
this.formToSubmit$ = new BehaviorSubject<Forms>(null);
constructor(){
this.updateForm();
}
updateForm(){
combineLatest(this.authService.user$, this.formToSubmit$).pipe(
switchMap(([user, form]) =>{
if(form == null) return;
return this.afs.collection('networks').doc(user.activeNetworkProfile.id).collection('companyProfiles').doc(user.activeCompanyProfile.id).collection('inspectionForms').doc(form.id).set(JSON.parse(JSON.stringify(form))).then(success=>{
this.formToSubmit$.next(null);
}).catch(err=>{
this.formToSubmit$.next(null);
});
})
);
}
這是以前的代碼,效果很好。
updateFormdd(form: Forms){
return Observable.create(observer=>{
this.authService.user$.subscribe(user=>{
this.afs.collection('networks').doc(user.activeNetworkProfile.id).collection('companyProfiles').doc(user.activeCompanyProfile.id).collection('inspectionForms').doc(form.id).set(JSON.parse(JSON.stringify(form))).then(success=>{
observer.next(success);
observer.complete();
}).catch(err=>{
observer.err(err);
});
})
})
}
但最終目標是弄清楚如何執行上述功能,但允許我像以下功能一樣組合多達3個可觀察到的值。
updateInspection(){
combineLatest(this.authService.user$, this.equipmentId$, this.inspectionToSubmit$).pipe(
switchMap(([user, equipmentId, form]) =>{
if(form == null) return;
return this.afs.collection('networks').doc(user.activeNetworkProfile.id).collection('companyProfiles').doc(user.activeCompanyProfile.id).collection('equipment').doc(equipmentId).set(JSON.parse(JSON.stringify(form))).then(success=>{
this.formToSubmit$.next(null);
}).catch(err=>{
this.formToSubmit$.next(null);
});
})
);
}
我只是想確保Im正確地使用了Observable。 謝謝
您的兩段代碼之間區別的關鍵是“訂閱”。
工作版本已訂閱。 由於您的可觀察物是冷可觀察物,因此只有在訂閱了某些內容后它們才會發出。
找出您要在哪里使用該可觀察對象,然后在其中添加訂閱。
this.formToSubmit$ = new BehaviorSubject<Forms>(null);
constructor(){
let mySubscription = this.updateForm().subscribe(
(dataFromCombineLatest) => {
// This subscription should cause the code inside the combine to fire
}
);
另外,如果這是在“組件”內部,則我建議在“ onInit”中而不是在構造函數中運行該位(我喜歡構造函數代碼精簡)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.