2017-08-03 21 views
0

异步http请求中返回值的问题。Angular 2 guard - 对用户的异步请求

如何等待订阅?

canActivate(
    route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot 
) { 
    if (this.auth.currentUser) { 
     return true; 
    } else { 
     this.auth.getUser() 
     .subscribe(resp => { 
      if (this.auth.currentUser) { 
      return true; 
      } else { 
      this.router.navigate(['login'], { 
       queryParams: { 
       returnUrl: state.url 
       } 
      }); 
      return false; 
      } 
     }) 
    } 
    } 

刷新页面时没有返回结果,我将重定向到主页面。

+1

可能是https://stackoverflow.com/questions/38425461/angular2-canactivate-calling-async-function和https://stackoverflow.com/questions/41377014/angular-2-canactivate-async的副本 –

回答

0

你没有在“别人的路返回任何东西:

canActivate(
    route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot 
) { 
    if (this.auth.currentUser) { 
    return true; 
    } else { 
    // This path do not return any value ! 

    this.auth.getUser() 
     .subscribe(resp => { 
     if (this.auth.currentUser) { 
      // This return is the return of your subscription callback function, not the canActivate one ! 
      return true; 
     } else { 
      this.router.navigate(['login'], { 
      queryParams: { 
       returnUrl: state.url 
      } 
      }); 
      // Same here 
      return false; 
     } 
     }) 
    } 
} 

您需要在第二个路径返回一个值(布尔,承诺或可观察):

canActivate(
    route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot 
) { 
    if (this.auth.currentUser) { 
    return true; 
    } else { 
    return this.auth.getUser() 
     .map(resp => { 
     if (this.auth.currentUser) { 
      // This return is the return of your subscription callback function, not the canActivate one ! 
      return true; 
     } else { 
      this.router.navigate(['login'], { 
      queryParams: { 
       returnUrl: state.url 
      } 
      }); 
      // Same here 
      return false; 
     } 
     }) 
     .first(); 
    } 
} 

使用map当你的回调返回一个布尔值时,你返回一个Observable。