到目前为止,我发现的最佳实践是首先创建全局服务并创建与http相关的方法
那里.即Get,Put,Post,Delete请求等,而不是通过使用这些方法调用您的API服务请求和
使用catch块和显示消息捕获错误,例如: –
原文链接:https://www.f2er.com/angularjs/143716.html那里.即Get,Put,Post,Delete请求等,而不是通过使用这些方法调用您的API服务请求和
使用catch块和显示消息捕获错误,例如: –
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 { ... } }
最好在引导您的应用程序时提供此服务作为依赖项,如下所示: –
bootstrap (APP,[GlobalService,.....])
比你想要调用请求的那个使用这些globalservice方法调用请求,如:
demo.ts
export class Demo { ... constructor(public GlobalService: GlobalService) { } getMethodFunction(){ this.GlobalService.PostRequest(url,data) .subscribe(res => {console.log(res),err => {console.log(err)} }); }
也可以看看
> catch is not working for http.get Angular2.
希望这可以帮到你.