2017-08-03 10 views
0

非同期http要求で戻り値に問題があります。角2のガード - 非同期のユーザーの要求

登録を待つ方法

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を返します。

関連する問題