我正在構建一個angular2 SPA。我正在使用內置的路由器組件,並且我已經實現了一個routeGuard。像這種警衛通常那樣,我檢查用戶是否登錄,如果他不是,那麼我希望將他發送到登錄屏幕。通常情況下,我使用的是#方案,因爲這個應用程序必須與其他代碼在同一個Web服務器上很好地發揮作用。router.navigate爲什麼在空白頁面上留下我沒有錯誤信息?
預期行爲:出現登錄屏幕。
實際行爲:路由「無處」。我坐着看着一個空白的屏幕。
路線後衛:
import { Injectable } from '@angular/core';
import { AuthenticationService } from './authentication.service';
import {
CanActivate, Router,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
import { GlobalsService } from "./globals.service";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _service: AuthenticationService, private router: Router, private _globals: GlobalsService) {
console.log("Auth Guard Ready!");
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
let url: string = state.url;
return new Promise<boolean>((resolve, reject) => {
if (this._service.checkLoggedIn()) {
console.log("User is logged in, possible to check for globals");
if (this._globals.globalsReady) {
console.log("Globals are already loaded, user may proceed to the page");
resolve(true);
return;
}
console.log("Globals are not ready yet, asking server for the data..");
this._globals.getGlobals()
.done(() => {
console.log("Globals are now loaded, user may proceed to the page");
resolve(true);
})
.error((error: any) => {
console.log("Error fetching globals. Navigation terminated");
console.log("Error: " + error);
resolve(false);
return;
});
} else {
// we couldnt find any way to auth, so sending user to login screen
console.log("User is not logged in - sending user to login page, no need for globals there");
this.router.navigate(["/login"]);
}
});
}
}
你能不保護正常到達您的登錄路由?你確定問題來自它嗎? –
你也應該'resolve(false);'當用戶重定向後沒有登錄。 –
是的,我可以正常登錄路線,我99%肯定它是來自後衛 – user230910