Search code examples
angularangular2-routingangular2-servicesangular2-http

Angular 2 how to redirect after REST http post/put as per the returned Status code


I'm trying to redirect/ reroute it to a specific page after success and failure of my http put request. the API returns some status codes as per the success or error (500, 401, 200 etc) I dont know how to handle this redirection

my service code is as shown below

putCustomer(body: string){
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers, method: 'put', withCredentials: true });

    return this.http.put(this._customerUrl, body, options)
        .map(res => res.json())
        .catch(this.handleError)
        .subscribe();
}
private handleError (error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || ' error');
}

Please help.

UPDATE: some minor adjustments to Fredrik's Answer:

import { Injectable } from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import { Router } from '@angular/router';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';

.........

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

      putCustomer(body: string){
            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers, method: 'put', withCredentials: true });

            //alert(body);
            return this.http
            .put(this._customerUrl, body, options)
            .do(res => {
            if(res.status === 200 ||res.status === 201) {
              this.router.navigate(['/success']);
            }
            else if(res.status === 401){
              this.router.navigate(['/error']);
            }
            else if(res.status >= 500){
              this.router.navigate(['/error']);
            }
          })
            .map(res => res.json())
            .catch(this.handleError)
            .subscribe();
        }
        private handleError (error: Response) {
            console.error(error);
            return Observable.throw(error.json().error || ' error');
        }

    }

Solution

  • Use the Response.status to get the status code from the http response. Then use the Router.navigate(...) to redirect. You can use the do operator on the Observable to perform the side effect of navigating to another route.

    Snippet:

    .do(res => {
       if(res.status === '200') this.router.navigate(['/somewhere']);
       else if(......) ...;
     })
    

    More full example to integrate with your code:

    import { Router } from '@angular/router'
    
    ...
    
    export class YourClass {
    
      constructor(router: Router, ...) {}
    
      putCustomer(body: string){
    
        ...
    
        return this.http
          .put(this._customerUrl, body, options)
          .do(res => {
            if(res.status === '200') this.router.navigate(['/somewhere']);
            else if(......) ...;
          })
          .map(res => res.json())
          .catch(this.handleError)
          .subscribe();
    }