angular - combineLatest behaviorSubject yüzünden mi tetiklenmiyor?
Aşağıdaki kod servis bileşenimden. Bir kullanıcı observable'ına ve bir BehaviorSubject içinde gönderilecek verilere ihtiyaç duyuyor. Güncellemek için form.service.formToSubmit$.next(form); çağrısını yapıyorum. Çünkü combineLatest kullanıcı observable'ı tetiklediğinde de çalışıyor, formToSubmit'in null olmadığını kontrol ediyorum ve gönderildikten sonra null olarak ayarlanıyor. Ama formToSubmit'i güncellediğimde çalışmıyor. Neredeyse her şeyi denedim.
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);
});
})
);
}
Bu, sorunsuz çalışan önceki koddur.
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);
});
})
})
}
Ama nihai amaç, yukarıdaki işlevi nasıl yapacağımı bulmak, ancak aşağıdaki işlevde olduğu gibi en fazla 3 gözlemlenebilir nesneyi birleştirmeme izin vermektir.
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);
});
})
);
}
Sadece observable'ları doğru kullandığımdan emin olmak istiyorum. Teşekkürler
Cevap #1
İki kod parçanız arasındaki farkın anahtarı "subscribe"'dır.
Çalışan sürümde bir abonelik vardı. Sizinki soğuk gözlemlenebilirler olduğu için, onlara bir şey abone olunana kadar yayım yapmayacaklardır.
O gözlemlenebilir öğeyi nerede tüketmek istediğinizi belirleyin ve ardından aboneliği oraya ekleyin.
this.formToSubmit$ = new BehaviorSubject<Forms>(null);
constructor(){
let mySubscription = this.updateForm().subscribe(
(dataFromCombineLatest) => {
// This subscription should cause the code inside the combine to fire
}
);
Ayrıca, eğer bu bir "bileşenin" içindeyse, o kısmı yapılandırıcı yerine "onInit" içinde çalıştırmanızı tavsiye ederim (yapılandırıcı kodumun sade olmasını severim).
