Mic*_*ger 5 rest error-handling angular
使用angular2 REST SERVICE调用并捕获任何全局异常以处理错误和显示自定义消息的最佳实践是什么.
有没有人经历过这个?
Par*_*ain 11
到目前为止,我发现的最佳实践是首先创建全局服务并创建与之相关的方法http
.即,对于获取,放置,发布,删除请求等,而不是通过使用这些方法调用您的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 { ... }
}
Run Code Online (Sandbox Code Playgroud)
最好在引导您的应用程序时提供此服务作为依赖项,如下所示: -
bootstrap (APP, [GlobalService, .....])
Run Code Online (Sandbox Code Playgroud)
比你想要调用请求的那些使用这些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)}
});
}
Run Code Online (Sandbox Code Playgroud)
也可以看看
希望这可以帮到你.
最好的解决方案是用Http
您自己的服务包装该服务。例如,您创建一个名为 的服务YourHttp
。YourHttp
应该实现与 相同的接口Http
。
注入Http
并YourHttp
让每个方法、、、get
..post
等put
调用该http
方法,然后捕获并处理任何错误。
现在在您的组件中注入YourHttp
. 为了获得额外的积分,请配置 DI 以YourHttp
在组件被注释为已Http
注入时进行注入。
更新
既然有了HttpClient,那么最好使用拦截器。
归档时间: |
|
查看次数: |
3874 次 |
最近记录: |