The best practice i have found so far is to firstly create global service and create your method related to http
there. i.e for Get, Put,Post ,Delete request etc. than via using these methods call your API service request and
catch there errors using catch block and display message as you want for example :-
Global_Service.ts
import {Injectable} from '@angular/core';
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/Rx';
@Injecable()
export class GlobalService {
public headers: Headers;
public requestoptions: RequestOptions;
public res: Response;
constructor(public http: Http) { }
public PostRequest(url: string, data: any): any {
this.headers = new Headers();
this.headers.append("Content-type", "application/json");
this.headers.append("Authorization", 'Bearer ' + key );
this.requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: this.headers,
body: JSON.stringify(data)
})
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
return [{ status: res.status, json: res }]
})
.catch((error: any) => { //catch Errors here using catch block
if (error.status === 500) {
// Display your message error here
}
else if (error.status === 400) {
// Display your message error here
}
});
}
public GetRequest(url: string, data: any): any { ... }
public PutRequest(url: string, data: any): any { ... }
public DeleteRequest(url: string, data: any): any { ... }
}
better to provide this service as dependency at the time of bootstraping your app like this :-
bootstrap (APP, [GlobalService, .....])
than whereever you want to call the request call the request using these globalservice methods like this :-
demo.ts
export class Demo {
...
constructor(public GlobalService: GlobalService) { }
getMethodFunction(){
this.GlobalService.PostRequest(url, data)
.subscribe(res => {console.log(res),
err => {console.log(err)}
});
}
see also