Angular 2: Prevent routing to new page if the service fails

In my Angular 2 app

home.html

<div>
<nav>
    <a [routerLink]="['Users']">Users</a>
</nav>
</div>

app.component.ts

import {Component} from 'angular2/core';
import {Router,RouteConfig, ROUTER_DIRECTIVES,RouterOutlet} from 'angular2/router';
import {UsersComponent} from './users/users'

@Component({
    selector: 'my-app',
    templateUrl: 'views/home.html',
    directives: [ROUTER_DIRECTIVES, RouterOutlet]
})
@RouteConfig([
{
    path: '/users',
    name: 'Users',
    component: UsersComponent
}
])
export class AppComponent { 

constructor(private _router:Router) {}
}

users.ts

import {Component} from 'angular2/core';
import {NgForm} from 'angular2/common';
import {DataService} from '../service';

@Component({
selector: 'my-app',
templateUrl: 'views/user.html'
})

export class UsersComponent {

constructor(private dataService: DataService) {
    this.dataService.getUserList().subscribe(
            (res) => {
                console.log('response=>' + res);
            },
            (error) => {
                console.log('failure);
            });
}
}

If there is any failure in service I want to prevent routing to the user.html page.

Any suggestions would be highly appreciated.

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

CanActivate is the right lifecycle callback to do this.

Currently using DI in @CanActivate() requires an ugly workaround (https://github.com/angular/angular/issues/4112) but the Angular team is working on improving that.