kkotak
kkotak

Reputation: 353

Angular2 Navigating to a path upon HTTP 401 error

I am using a service in Angular2 that issues HTTP requests to a RESTful API server. I need to catch the 401 error and redirect the user to /login page. For some reason the router.nagivate(['/login']) does not get executed in the code below. Note that I have followed the instructions in this answer Angular 2 redirect in http/rxjs catch callback causes TypeError: Cannot read property 'subscribe' of undefined, but my code doesn't redirect.

search(term: string): Observable<[]> {
return this.http
  .get(this.userListUrl+'User?name='+term')
  .map((r: Response) => r.json())
  .catch(this.handleError);

}

  private handleError(error: any): Observable<any>{
if(error.status == 401) {
  console.error('An error occurred', error.status);
  this.router.navigate(['/login']);
  return Observable.of([]);
} else {
  let errMsg = error.statusText || 'Server error';
  console.error(errMsg); // log to console instead
  return Observable.throw(errMsg);
}}

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

Edit: Updated handlerError code.

Upvotes: 0

Views: 742

Answers (1)

SeleM
SeleM

Reputation: 9638

In ui-router-ng2 (import { UIRouter } from 'ui-router-ng2';), you can navigate programmatically by injecting router: UIRouter and calling the go method: router.stateService.go('somestate')

EXEMPLE:

in your app.routing.ts :

export const ROUTES: any = [
  {url: '/login',             name: 'Login',      component: LoginComponent}
]

Then you function should be :

if(error.status == 401) {
  this.router.stateService.go('Login');
}

Where the router is

private router:      UIRouter; 

in your Constructor.

Upvotes: 0

Related Questions