Najlepszą praktyką, jaką dotychczas odkryłem, jest utworzenie usługi globalnej i utworzenie w niej metody związanej z http
. tj get, put, Post, Usuń itp niż poprzez żądania używając metody te nazywają swoje żądanie usługi API i połów tam błędów za pomocą bloku catch i komunikat na wyświetlaczu, jak chcesz, na przykład: -
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 { ... }
}
lepiej do świadczenia tej usługi jako zależność w czasie bootstraping swoją aplikację tak: -
bootstrap (APP, [GlobalService, .....])
niż gdziekolwiek chcesz zadzwonić żądanie wywołać żądania za pomocą tych metod globalservice jak to: -
demo.ts
export class Demo {
...
constructor(public GlobalService: GlobalService) { }
getMethodFunction(){
this.GlobalService.PostRequest(url, data)
.subscribe(res => {console.log(res),
err => {console.log(err)}
});
}
zobaczyć również
Możecie poszukać http://stackoverflow.com/questions/37609725/how-to-inject-my-service-to-exceptionhandler lub http://stackoverflow.com/questions/35274523/handling- angular-2-http-errors-centrally –
Trochę się spóźniłem na tę grę, ale Thierry Templier ma całkiem niezłą odpowiedź na temat rozszerzenia klasy http dla Angular2. http://stackoverflow.com/a/37744126/2106702 –
https://angular.io/docs/ts/latest/guide/server-communication.html#!#http-client –