Loading…

How we can handle errors in Angular 2?

All Angular 2 apps have the option of finding and handling errors. This can be done by including the ReactJS catch library and using the catch function.

Example

                                        

We have add this code in the product.service.ts file
import { Injectable } from '@angular/core';
import { Http , Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { IProduct } from './product';

@Injectable()
export class ProdService {
   private _producturl = 'app/products.json';
   constructor(private _http: Http){}


   getproducts(): Observable {
       return this._http.get(this._producturl)
       .map((response: Response) => response.json())
       .do(data => console.log(JSON.stringify(data)))
       .catch(this.handleError);
   }

   private handleError(error: Response) {
      console.error(error);
      return Observable.throw(error.json().error());
  }
}

Suggest An Answer

No suggestions avaliable!

Latest post from Angular 2 Interview Questions

Ask Question