繁体   English   中英

CombineLatest是否不会因为behaviorSubject而开火?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM