Angular2: how to redirect if API returns an error?

In my service, I want to describe a behavior when user is being redirected if not authorized.

export class MessagesService {
    constructor (private http: Http) {}

    private _usersUrl = '/users.json';  // URL to web api


    getUsers() {
        return this.http.get(this._usersUrl)
            .map(res => <User[]> res.json().data)
            .catch(this.handleError);
    }

    private handleError (error: Response) {

        if (error.status == 401) {
            // How do I tell Angular to navigate LoginComponent from here?
        } else {
            return Observable.throw(error.json().error || 'Server error');
        }
    }
}

My questions are:

  • Is it even possible?
  • Is that a good practice?
    • If yes, how do I perform that?
    • If no, how else can I do that?

2
Leave a Reply

avatar
2 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

My approach was to create my own request service and have an interceptor function which wraps the actual request to handle 401 and 403 etc. Have included it below if you want to have a look at it. import {Injectable} from "@angular/core" import {Subscription, Observable} from "rxjs" import {TokenModel} from "../../models/token.model" import {TokenService} from "../authentication/token.service" import {Http, Headers, URLSearchParams, RequestOptions, Request, RequestMethod} from "@angular/http" import {Router} from "@angular/router" @Injectable() export class RequestService { private baseUrl: string; private subscription: Subscription; private token: TokenModel; constructor(public tokenService: TokenService, public http: Http, public router: Router) { this.baseUrl = `${process.env.API_URL}/example`; this.subscription = this.tokenService.token$.subscribe(token => this.token… Read more »

Jason
Guest

One direction we’ve been approaching this on our team is by implementing an API client class. This API client wraps the original Http service. The idea is that since the Http service produces observables you can easily extend its behavior by adding operators like map, flatMap and catch operators to the original observable produced by the Http service. I think you will find this example a useful starting point to fix the problem you’re having. import { ApiRequestOptions } from './api-request-options.service'; import { Http, Response, RequestOptions, ResponseContentType } from '@angular/http'; import 'rxjs/add/observable/zip'; import 'rxjs/add/operator/map'; import { Observable } from 'rxjs/Rx';… Read more »