Angular Route Guard CanActivate停止路由

时间:2017-10-06 14:25:06

标签: angular angular-routing angular-router-guards canactivate

我正在尝试查看用户已选择公司登录的天气。如果他们选择那么他们会看到那些公司员工。否则,我们将重定向到登录页面。

我使用Angular Route Guard来做到这一点。但它没有继续路线并停在那里,尽管我回归真实。如何继续路线

路线配置

const appRoutes: Routes = [
    { path: "employees", component: EmployeeListComponent, canActivate: [AuthGuard] },
    { path: "", redirectTo: "/employees", pathMatch: "full" },
    { path: "login", component: LoginComponent },
    { path: "**", component: PageNotFoundComponent }
];

Auth Guard

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AppService } from '../../app/app.service';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private appService: AppService, private router: Router) {

    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        let user: IUserViewData;
        var _this = this;

        this.appService.getUserViewData()
            .subscribe(
                (response: IUserViewData) => {
                    user = response;
                    if (user.LoggedInCompany != null) {

                        return true;
                    } else {
                        _this.router.navigate(['/login']);
                        return false;
                    }
            },
            (error: any) => { });

        return false;
    }
}

1 个答案:

答案 0 :(得分:1)

更改订阅地图,返回Observable<boolean>

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    var _this = this;
    return this.appService.getUserViewData().map(user => {
        if (user.LoggedInCompany != null) {
            return true;
        } else {
            _this.router.navigate(['/login']);
            return false;
        }
    }); 
}