2017-08-17 97 views
0

響應這是我的代碼如何等待從服務角度2

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { 
    let isAuthenticated: boolean = false 
    this.authServiceLocal.isAuthenticated().then(response => isAuthenticated = response) 

    if(isAuthenticated){ 
     return true 
    } 

    // not logged in so redirect to login page with the return url 
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }}); 
    return false 

    } 

我想等待服務的響應然後檢查isAuthenticated 我正在從服務器真假值的值如預期的那樣,在API調用中沒有問題。

回答

0

您可以等待響應,一旦數據available.Change代碼以下

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<any> { 
     let isAuthenticated: boolean = false; 
     let result = new EventEmitter<boolean>(); 
     return this.authServiceLocal.isAuthenticated().then(response => {isAuthenticated = response; 
    if(isAuthenticated){ 

     } 
     else { 
      this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }}); 
     result.emit(false); 
     result.complete(); 

     } 

     // not logged in so redirect to login page with the return url 

    }) 
    return result; 
     } 
+0

類型「無極」做了手術是不能分配給鍵入「布爾」它表明 –

+0

看我的更新的答案.. –

+0

canActivate沒有等待來自auth服務的響應。 canActivate函數只是自己完成而沒有返回任何值。 –