【问题标题】:Best practice for call REST services and global error catching with angular2 [closed]使用 angular2 调用 REST 服务和全局错误捕获的最佳实践 [关闭]
【发布时间】:2016-10-11 03:14:01
【问题描述】:

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

有没有人有这方面的经验?

【问题讨论】:

标签: rest error-handling angular


【解决方案1】:

到目前为止我发现的最佳实践是首先创建全局服务并创建与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 { ... }
 }

最好在像这样引导您的应用程序时将此服务作为依赖项提供:-

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)}
             });
    }

另见

【讨论】:

    【解决方案2】:

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

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

    现在在你的组件中注入YourHttp。为了获得额外的功劳,请配置 DI 以在您的组件被注释为注入 Http 时注入 YourHttp

    更新

    现在有了HttpClient,最好使用拦截器。

    【讨论】:

      猜你喜欢
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      • 2013-05-04
      • 2017-11-26
      • 2020-04-07
      • 1970-01-01
      相关资源
      最近更新 更多