为什么router.navigate将我留在空白页面而没有错误消息?

时间:2017-04-19 10:14:12

标签: angular typescript angular2-routing

我正在建造一个angular2 SPA。我正在使用内置的路由器组件,我已经实现了routeGuard。像这种警卫一样,我检查用户是否登录,如果不是,那么我希望将他发送到登录界面。与平时不同的是,我正在使用#方案,因为这个应用程序必须与同一个Web服务器中的其他代码很好地配合。

预期行为:显示登录屏幕。

实际行为:路由“无处”。我坐着看着一个空白的屏幕。

Route Guard:

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"]);
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

警卫需要知道如何处理所有案件。

当用户未登录时(重定向后)添加resolve(false);将会起到作用