Angular 2 – Routing – CanActivate work with Observable

You should upgrade “@angular/router” to the latest . e.g.”3.0.0-alpha.8″ modify AuthGuard.ts @Injectable() export class AuthGuard implements CanActivate { constructor(private loginService: LoginService, private router: Router) {} canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) { return this.loginService .isLoggedIn() .map((e) => { if (e) { return true; } }) .catch(() => { this.router.navigate([‘/login’]); return Observable.of(false); }); } } If you have … Read more

How to unit test a component that depends on parameters from ActivatedRoute?

The simplest way to do this is to just use the useValue attribute and provide an Observable of the value you want to mock. RxJS < 6 import { Observable } from ‘rxjs/Observable’; import ‘rxjs/add/observable/of’; … { provide: ActivatedRoute, useValue: { params: Observable.of({id: 123}) } } RxJS >= 6 import { of } from ‘rxjs’; … Read more

Pass parameter into route guard

Instead of using forRole(), you can do this: { path: ‘super-user-stuff’, component: SuperUserStuffComponent, canActivate: [RoleGuard], data: {roles: [‘SuperAdmin’, …]} } and use this in your RoleGuard canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean { let roles = route.data.roles as Array<string>; … }

Angular2 router-deprecated dependencies not being loaded

In Angular2 RC.0 you might need to add ‘@angular/router-deprecated’: { main: ‘index.js’, defaultExtension: ‘js’ }, to your packages in config.js or this if you want to use the new router: ‘@angular/router’: { main: ‘index.js’, defaultExtension: ‘js’ }, Example config.js from the rc.0 Plunker (function(global) { var ngVer=”@2.0.0-rc.0″; // lock in the angular package version; do … Read more

Angular 2 router resolve with Observable

Don’t call subscribe() in your service and instead let the route subscribe. Change return this.searchService.searchFields().subscribe(fields => { to import ‘rxjs/add/operator/first’ // in imports return this.searchService.searchFields().map(fields => { … }).first(); This way an Observable is returned instead of a Subscription (which is returned by subscribe()). Currently the router waits for the observable to close. You can … Read more

Redirect to a different component inside @CanActivate in Angular2

As of today, with latest @angular/router 3.0.0-rc.1, here are a couple of references on how to do that through CanActivate guards on routes: angular 2 reference Two answers to this SO question, by Nilz11 and by Jason The main gist of logic looks like: // … canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { if (this.authService.isLoggedIn) { // … Read more