2017-04-18 36 views
0

我有一個Web應用程序,其中有一個JWT令牌傳遞給管理服務。此JWT來自查詢URL,因爲存在來自其他應用程序的重定向。服務中的構造函數檢查該URL併爲其設置token值(如果該參數在那裏)。角度使canActivateGuard異步

我面臨的問題是canActivateGuard過早起火。當這被稱爲觀察到讓JWT在服務中還沒有解決,所以當警衛被解僱時JWT總是不在那裏。

我必須弄明白,爲了使這項工作isLoggedIn()在AdminService有可能成爲一個可觀察的是聽的URL的變化,而在後衛canActivate()有訂閱,但不能使這個工程。

下面的代碼是我走到這一步,

// Admin Service 
import { Injectable } from '@angular/core'; 
import { Observable } from 'rxjs/Rx'; 
import 'rxjs/Rx'; 

import {Router, ActivatedRoute, Params} from '@angular/router'; 

@Injectable() 
export class AdminService { 

    token: string; 

    constructor(private activatedRoute: ActivatedRoute) { 

     activatedRoute.queryParams.subscribe(
      (params) => { 
       console.log('queryParams', params); 
       if(localStorage.getItem('jwt')) { 
        this.token = localStorage.getItem('jwt'); 
       } 
       else if(params['jwt']) { 
        localStorage.setItem('jwt', params['jwt']); 
        this.token = params['jwt']; 
       } 
      }); 
    } 


    // Check that JWT is in local storage and valid 
    isLoggedin() { 
     return (localStorage.getItem('jwt') !== null && localStorage.getItem('jwt') !== 'undefined'); 
    } 
} 


// Can Activate guard 
// Note that this.authService.isLoggedIn() is called before the set JWT in the service is solved 

@Injectable() 
export class AuthGuard implements CanActivate { 

    constructor(
    private authService: AdminService, 
    private router: Router 
) { 
    } 

    canActivate() { 
     if (this.authService.isLoggedin()) { 
      console.log('all ok, proceed navigation to routed component') 
      return true; 
     } 
     else { 
      // start a new navigation to redirect to login page 
      this.router.navigate(['/unauthorized']); 
      return false; 
     } 
    } 
} 
+0

您是否嘗試過使用'snapshot'? 'activatedRoute.snapshot.queryParams'。 – developer033

+0

不知道爲什麼會改變什麼? – greatTeacherOnizuka

+0

*「我正面臨的問題是canActivateGuard過早啓動,當這被稱爲獲取服務中的JWT的observable尚未解決*」。所以..使用'快照'你不必訂閱JWT .. – developer033

回答

0

使用ActivatedRouteSnapshotRouterStateSnapshot您的問題將得到解決,而且你不需要你的服務認購JWT。

下面是我在Angular2應用程序中使用的代碼示例。

AUTH-guard.ts

import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; 
import { Injectable } from '@angular/core'; 
import { Observable } from 'rxjs/Observable'; 
import { AuthCookie } from '../shared/services/auth-cookies-handler'; 

@Injectable() 
export default class AuthGuard implements CanActivate { 
    constructor(private router: Router, private _authCookie: AuthCookie) { } 

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { 
     if (this._authCookie.getAuth()) { 
      return true; 
     } 
     else { 
      this.router.navigate(['/login']); 
      return false; 
     } 
    } 
} 

希望這會幫助你。