nusje2000
nusje2000

Reputation: 503

Angular 2 router.navigate() in HTTP error handler

I'm trying to make a system in angular that navigates to the login page if the server returns an 401 error, I tried this but it doesn't navigate:

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable }     from 'rxjs/Observable';
import { Router } from '@angular/router';

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthService {

  private heroesUrl = 'http://localhost:8000/auth/loggedIn';

  constructor (private http: Http, private router: Router) {}

  loggedIn (): Observable<string|number> {
    return this.http.get(this.heroesUrl)
      .map(res => { return res.json(); })
      .catch(this.handleError);
  }

  private handleError (error: Response|any) {
    if (error.status == 401) {
      this.router.navigate(['/path_to_login_page']);
      return error.status;
    }
  }
}

And I already checked the response from the server and I also console logged error.status == 401, and it did return true, can anyone help me with this problem.

Thanks in advance

Upvotes: 3

Views: 7945

Answers (2)

jonas
jonas

Reputation: 1652

What I had to do was to incapsulate the this.router.navigate([]) inside an setTimeout(() => ...) function.

So this would like something like

private handleError (error: Response|any) {
    if (error.status == 401) {
      setTimeout(() => this.router.navigate(['/path_to_login_page']));
      return error.status;
    }
  }

I know that this particular question is answered before, I just put it out here in case others like me ends up here :)

Upvotes: 1

seidme
seidme

Reputation: 13048

Angular provides two options for navigating (Router Class):

Navigate based on the provided array of commands and a starting point. If no starting route is provided, the navigation is absolute. Usage:

this.router.navigate(['team', 33, 'user', 11], {relativeTo: route});

Navigate based on the provided url. This navigation is always absolute. Usage:

this.router.navigateByUrl('/team/33/user/11');

If you attempted to use the first option, remove the / prior the command:

this.router.navigate(['path_to_login_page']);

Upvotes: 4

Related Questions