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;
}
});
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments