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

时间:2016-06-10 08:23:24

标签: rest error-handling angular

使用angular2 REST SERVICE调用并捕获任何全局异常以处理错误和显示自定义消息的最佳做法是什么。

有没有经历过这个?

2 个答案:

答案 0 :(得分:11)

到目前为止,我发现的最佳做法是首先创建全局服务并创建与http相关的方法 那里。即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, .....])

如果您想要调用请求,请使用以下全局服务方法调用请求: -

demo.ts

export class Demo {
     ...
    constructor(public GlobalService: GlobalService) { }

    getMethodFunction(){
       this.GlobalService.PostRequest(url, data)
        .subscribe(res => {console.log(res),
                   err => {console.log(err)}
             });
    }

另见

答案 1 :(得分:2)

最佳解决方案是使用您自己的服务包装Http服务。例如,您创建了一个名为YourHttp的服务。 YourHttp应实现与Http相同的界面。

Http注入YourHttp并让每种方法getpostput等调用http方法,然后捕获并处理任何错误。

现在在您的组件中注入YourHttp。如需额外信用,请在注释组件注入YourHttp时将DI配置为注入Http

更新

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

相关问题