Angular 2+ wait for method / observable to complete

前端 未结 2 1879
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 10:10

I need to check te back-end for authentication status, however te code completes before te observable return is finished. Which would result in an undifined.



        
相关标签:
2条回答
  • 2020-12-13 10:33

    Solved the issue with async / await and promise

    The LoginService first import toPromise:

    import 'rxjs/add/operator/toPromise';
    

    Then created an async method in the LoginService

      async isAuthenticated(){
         const response = await this.http.get('/login/authenticated').toPromise();
         return response.json();
      }
    

    Then in the component:

    async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        this.loginStatus = await this.loginService.isAuthenticated();
    
        console.log("LOGGED IN STATUS: " + this.loginStatus);
    
        if (this.loginStatus == true){
            return true;
        }
    
        // not logged in so redirect to login page with the return url
        this.router.navigate(['/layout/login'], { queryParams: { returnUrl: state.url } });    
    }
    
    0 讨论(0)
  • 2020-12-13 10:42

    You can return the observable as Observable<boolean>

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        return this.loginService.isAuthenticated()
            .map(status => {
                console.log(status);
                this.authenticated = status;
                return true;
            }).catch((err) => {
                console.log(err);
                return Observable.of(false);
            });
    }
    
    0 讨论(0)
提交回复
热议问题