2017-08-03 39 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。