调用REST服务和使用angular2捕获全局错误的最佳实践

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)

也可以看看


Mar*_*tin 2

最好的解决方案是用Http您自己的服务包装该服务。例如,您创建一个名为 的服务YourHttpYourHttp应该实现与 相同的接口Http

注入HttpYourHttp让每个方法、、、get..postput调用该http方法,然后捕获并处理任何错误。

现在在您的组件中注入YourHttp. 为了获得额外的积分,请配置 DI 以YourHttp在组件被注释为已Http注入时进行注入。

更新

既然有了HttpClient,那么最好使用拦截器。