3

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

2 Answers 2

4

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']);
Sign up to request clarification or add additional context in comments.

3 Comments

I cant try it now but I think this should work, thanks.
@nusje2000 have you tried it, and did it solve your problem?
Yea sorry, I forgot about it but yea it did.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.