Javascript Angular/Typescript/Firestore-如何在if语句中返回可观察值

Javascript Angular/Typescript/Firestore-如何在if语句中返回可观察值,javascript,angular,typescript,google-cloud-firestore,scoping,Javascript,Angular,Typescript,Google Cloud Firestore,Scoping,我正在使用angular和firestore。我正在检查firestore,查看我的路线守卫中的值 我发现在页面刷新时,它返回为未定义。但是,如果我只是硬编码返回true或false,它就可以工作 if语句中的任何日志都会正确返回,但由于某种原因,似乎没有更新全局变量 如果我使用我的站点导航返回到根目录并在我的站点中导航,它将正常工作。但是,当我刷新页面时,它返回为未定义 这可能是一个范围问题吗 路障 从“@angular/core”导入{Injectable}; 从'@angular/Rout

我正在使用angular和firestore。我正在检查firestore,查看我的路线守卫中的值

我发现在页面刷新时,它返回为未定义。但是,如果我只是硬编码返回true或false,它就可以工作

if语句中的任何日志都会正确返回,但由于某种原因,似乎没有更新全局变量

如果我使用我的站点导航返回到根目录并在我的站点中导航,它将正常工作。但是,当我刷新页面时,它返回为未定义

这可能是一个范围问题吗

路障

从“@angular/core”导入{Injectable}; 从'@angular/Router'导入{ActivatedRouteSnapshot,RouterStateSnashot,CanActivate,Router}; 从“/auth.service”导入{AuthService}; 从“angularfire2/firestore”导入{AngularFirestore、AngularFirestoreCollection、AngularFirestoreDocument}; 从'rxjs/Subscription'导入{Subscription}; //测试 从“rxjs/Observable”导入{Observable}; 从'angularfire2/auth'导入{AngularFireAuth}; @注射的 导出类CheckBillingService实现CanActivate{ 私人认购:认购; 私有用户BillingDocRef:AngularFirestoreDocument; 用户计费:可观察; 公共账户:可观察 constructorprivate authService:authService, 专用路由器:路由器, 私人授权:AngularFireAuth, 私有只读afs:AngularFirestore{} 可激活的:可观察的{ this.authService.user.subscribeuser=>{ 如果用户{ var userId=user.uid; this.userBillingDocRef=this.afs.doc'user_billing/${userId}'; this.userBilling=this.userBillingDocRef.snapshotChanges; this.userBilling.subscribevalue=>{ 常量数据=value.payload.data; 如果data.account\u status==活动{ this.activeAccount=可观察的oftrue; log'inside if statement for active=',this.activeAccount; }否则{ this.activeAccount=可观察的offalse; log'inside if statement for not active=',this.activeAccount; 这个.router.navigate['resubscribe']; 可观察的返回值; } console.log'userBilling.subscribe=',this.activeAccount; }; log'justoutheruserbilling.subscribe=',this.activeAccount; } }; //刷新我的页面时,返回为未定义。 //如果我导航到正确的页面并在网站上工作,它会工作得很好 //但是,刷新返回未定义的。 console.log'out of auth=',this.activeAccount; 返回此.activeAccount; } }
根据您的代码,页面将在您的可观察方法返回之前运行,因为它是异步运行的,而不是像这样返回完整的可观察方法

 canActivate(): Observable<boolean> {

    return Observable.create(observer=> {
this.authService.user.subscribe((user) => {

                if (user) {

                    var userId = user.uid;

                    this.userBillingDocRef = this.afs.doc('user_billing/${userId}');

                    this.userBilling = this.userBillingDocRef.snapshotChanges();
                    this.userBilling.subscribe((value) => {

                        const data = value.payload.data();

                        if (data.account_status == "Active") {
                            this.activeAccount = Observable.of(true);
 // observe here 
        observer.next(true)
                            console.log('inside if statement for active = ', this.activeAccount);
                        } else {
                            this.activeAccount = Observable.of(false);
          // observe here 
        observer.next(false)
                            console.log('inside if statement for not active = ', this.activeAccount);
                            this.router.navigate(['resubscribe']);
                        }

                        console.log('userBilling.subscribe = ', this.activeAccount);
                    });

                    console.log('just outside userBilling.subscribe = ', this.activeAccount);

                }

            });
    });


            // When refreshig my page, this returns as undefined.
            // If I navigate to the correct page and work my way through the site it works fine
            // However, refresh returns undefined.

            console.log('out of auth = ', this.activeAccount);

        }

根据您的代码,页面将在您的可观察方法返回之前运行,因为它是异步运行的,而不是像这样返回完整的可观察方法

 canActivate(): Observable<boolean> {

    return Observable.create(observer=> {
this.authService.user.subscribe((user) => {

                if (user) {

                    var userId = user.uid;

                    this.userBillingDocRef = this.afs.doc('user_billing/${userId}');

                    this.userBilling = this.userBillingDocRef.snapshotChanges();
                    this.userBilling.subscribe((value) => {

                        const data = value.payload.data();

                        if (data.account_status == "Active") {
                            this.activeAccount = Observable.of(true);
 // observe here 
        observer.next(true)
                            console.log('inside if statement for active = ', this.activeAccount);
                        } else {
                            this.activeAccount = Observable.of(false);
          // observe here 
        observer.next(false)
                            console.log('inside if statement for not active = ', this.activeAccount);
                            this.router.navigate(['resubscribe']);
                        }

                        console.log('userBilling.subscribe = ', this.activeAccount);
                    });

                    console.log('just outside userBilling.subscribe = ', this.activeAccount);

                }

            });
    });


            // When refreshig my page, this returns as undefined.
            // If I navigate to the correct page and work my way through the site it works fine
            // However, refresh returns undefined.

            console.log('out of auth = ', this.activeAccount);

        }
可观测数据可以是异步的;它们通常用于此目的。在这种情况下,subscribe外部的代码在内部subscribe之前执行

这就是为什么它似乎没有更新变量。是的,但您没有在正确的时间访问它们。当您硬编码这些值时,它会起作用,因为订阅是同步执行的。

可观察对象可以是异步的;它们通常用于此目的。在这种情况下,subscribe外部的代码在内部subscribe之前执行


这就是为什么它似乎没有更新变量。是的,但您没有在正确的时间访问它们。当您对值进行硬编码时,它会起作用,因为订阅是同步执行的。

这很完美。非常感谢您的快速回复。对于新手来说,这是一个非常好的信息。我会在2分钟内将此标记为答案。谢谢您的更新Theo。如果有人用资源和代码为这个问题提供了一些真正的教育价值,得到这样的回答是很好的。非常感谢。这太完美了。非常感谢您的快速回复。对于新手来说,这是一个非常好的信息。我会在2分钟内将此标记为答案。谢谢您的更新Theo。如果有人用资源和代码为这个问题提供了一些真正的教育价值,得到这样的回答是很好的。非常感谢,谢谢拉扎尔。我感谢你的答复。西奥的上述回答就是答案,与你所说的相符。再次感谢。既然你不在,那么:没必要在评论中亲自感谢。投票表决和/或接受答案通常是一种方式。高兴哟
你找到了解决办法!谢谢拉扎尔。我感谢你的答复。西奥的上述回答就是答案,与你所说的相符。再次感谢。既然你不在,那么:没必要在评论中亲自感谢。投票表决和/或接受答案通常是一种方式。很高兴你找到了解决办法!