加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:58:28 所属栏目:安全 来源:网络整理
导读:使用angular2 REST SERVICE调用并捕获任何全局异常以处理错误和显示自定义消息的最佳实践是什么. 有没有人经历过这个? 到目前为止,我发现的最佳实践是首先创建全局服务并创建与http相关的方法 那里.即Get,Put,Post,Delete请求等,而不是通过使用这些方法调用
使用angular2 REST SERVICE调用并捕获任何全局异常以处理错误和显示自定义消息的最佳实践是什么.

有没有人经历过这个?

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

比你想要调用请求的那个使用这些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.

希望这可以帮到你.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读