[英]Angular2 CanActivate undefined
我想在我的應用中添加一些限制路線。 我寫了一個Guard,就像在這里的文檔中解釋的那樣,但是我嘗試不使用打字稿來實現它: https ://angular.io/docs/ts/latest/guide/router.html#!#guards
我的Guard看起來像這樣,但我不能使用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]];
}
}
那是因為這是一個interface
。 僅在TypeScript
中的類型提示和靜態鍵入中使用。 在編譯的JavaScript
沒有實際輸出。 因此,它將在邏輯上評估為undefined
。
你的代碼可能無法工作的一個原因是因為你用checkIfLoggedIn
並定義一個函數_checkIfLoggedIn
(在_
中缺少調用)。
另一個原因可能是getUser
是一個異步函數。 在這種情況下,您應該返回一個Observable<boolean>
或Promise<boolean>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.