简体   繁体   中英

canActivate returns unwanted value

I have a canActivate method that I would like to implement, but for some reason(which I'm probably not aware of since I'm a newbie) the return value is happening before the subsribe completes.

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { debugger; this.ms_zehut = JSON.parse(localStorage.getItem('id')); this.adminService.checkIsAdmin().subscribe(res=>{ this.isCanActivate = true; },error=>{ debugger; this.isCanActivate = false; this.router.navigateByUrl("/foo"); }); return this.isCanActivate; } 

  checkIsAdmin() : Observable<ResultOfOperation<object>> { const headers = new HttpHeaders().set('Content-Type','application/json'); console.log("service before get"); return this._httpClient.get<ResultOfOperation<Object>>(AppSettings.getIsAdmin, {headers: headers}) .pipe( tap(data => { console.log("service get result", data); }) ); } 

What should I do in order to get the result of subscription before this.canActivate is being returned?

canActivate also accepts observable. if the return value is an observable it will subscribe to it implicitly.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean>
    {
        debugger;
        this.ms_zehut = JSON.parse(localStorage.getItem('id'));

        return this.adminService.checkIsAdmin()
    }

use catchError to handle the failed response

 return this._httpClient.get<ResultOfOperation<Object>>(AppSettings.getIsAdmin, {headers: headers})
            .pipe(
                tap(data => { 
                    console.log("service get result", data);
                }),
                catchError(err = > { 
                  this.router.navigateByUrl("/foo");
                })
            );

The issue here is code won't wait till the API is finished.

Try async/await

more information:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Change the service file implementing async/await as following

async checkIsAdmin() {
    const headers = new HttpHeaders().set("Content-Type", "application/json");
    console.log("service before get");

    const response = await this. _httpClient.get<ResultOfOperation<Object>>(AppSettings.getIsAdmin, {headers});
    return response; // check here if not json use response.json()
}

In the guard file

async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.isCanActivate = await this.adminService.checkIsAdmin();


    // check the if the response returned is of 'error' or ResultOfOperation<object>
    if (this.isCanActivate === your object type){
        return true;
    }

    // not logged in so redirect
    this.router.navigateByUrl("/foo");   
}

Hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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