简体   繁体   中英

Angular Route Guard CanActivate stops routing

I am trying to check weather the user has already selected a company to login. If they select then they see those company employees. Otherwise, we will redirect to login page.

I have used Angular Route Guard to do this. But its not continuing the route and stops there, though I return true. How to continue route

Route config

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;
    }
}

Change subscribe to map that returns 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;
        }
    }); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM