2016-11-01 92 views
0

我想在我的應用程序中添加一些受限制的路線。我寫了一個警衛像他們在這裏的文檔說明,但我嘗試去實現它沒有打字稿:https://angular.io/docs/ts/latest/guide/router.html#!#guardsAngular2 CanActivate undefined

我的後衛是這樣,但我不能使用CanActivate,因爲它不是在@angular/router V3.1.1

定義
import { Router, CanActivate } from '@angular/router'; 
import { AuthService } from './app.auth.service'; 

console.log(CanActivate); // undefined 

export class AuthGuard extends CanActivate { 
    constructor(AuthService) { 
    super(); 
    this._authService = AuthService; 
    } 

    canActivate() { 
     return this.checkIfLoggedIn(); 
    } 

    _checkIfLoggedIn() { 
     const user = this._authService.getUser(); 

     return user; 
    } 

    static get parameters() { 
    return [[AuthService]]; 
    } 
} 

任何想法?

編輯

這種方法按預期工作,感謝@PierreDuc的幫助我回到賽場上。

import { Router } from '@angular/router'; 
import { AuthService } from './app.auth.service'; 

export class AuthGuard { 
    constructor(AuthService, Router) { 
    this._authService = AuthService; 
    this._router = Router; 
    } 

    canActivate() { 
    if (this._authService.isLoggedIn()) { 
     return true; 
    } 

    this._router.navigate(['/login']); 
    return false; 
    } 

    static get parameters() { 
    return [[AuthService], [Router]]; 
    } 
} 

回答

1

這是因爲它是一個interface。這僅用於TypeScript中的類型提示和靜態輸入。它在編譯的JavaScript中沒有實際的輸出。出於這個原因,它將在邏輯上評估爲undefined

你的代碼可能無法工作的一個原因是因爲你用checkIfLoggedIn並定義_checkIfLoggedIn一個功能(_丟失呼叫)。

另一個原因可能是getUser是一個異步函數。在這種情況下,您應該返回Observable<boolean>Promise<boolean>

+0

好的,謝謝。接口是關鍵字。接口不是ES6的一部分,對吧?!你有一個想法如何使用es6和沒有TypeScript的guard/canActive概念? –

+0

@ d-bro82沒有必要擴展它來啓用任何方法,與在TypeScript中工作的方式一樣,它也應該在ES6中工作。 – PierreDuc

+0

知道了!這非常有幫助,ty –