2017-08-17 95 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函数只是自己完成而没有返回任何值。 –