Angular 2+ wait for method / observable to complete

I need to verify the source code for authentication, however the te code exits before verification is complete. Which will lead to uncontrollable.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.isAuthenticated();        
    return this.authenticated; 
}

isAuthenticated(){
    this.loginService.isAuthenticated()
        .subscribe(status => this.authenticated = status)
} 

How can I change this code, so I wait until the observable completes to get an authenticated status before the code returns.

Note. The canActivate Angular method prevents me from writing code, as shown below:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.loginService.isAuthenticated()
        .subscribe(status => {
            this.authenticated = status;
            return this.authenticated;
        });
}

This results in the following error:

'AuthGuard' 'CanActivate'.
'canActivate' .     Type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) = > void' '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) = > boolean | | Pr... '.        'void' 'boolean' | Promise".

.

+4
2

async/await

LoginService forPromise:

import 'rxjs/add/operator/toPromise';

LoginService

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

:

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 } });    
}
+7

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);
        });
}
+4

Source: https://habr.com/ru/post/1677068/


All Articles