Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 228
nusje2000 Avatar asked Aug 23 '26 10:08

nusje2000


2 Answers

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']);
like image 97
seidme Avatar answered Aug 27 '26 00:08

seidme


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 :)

like image 41
jonas Avatar answered Aug 26 '26 22:08

jonas