【问题标题】:Best practice for handling error in Angular2Angular2 中处理错误的最佳实践
【发布时间】:2017-02-02 09:14:24
【问题描述】:

您好,我正在尝试接收从 catch 块(服务)发送的错误。 在多个组件中,我需要显示一个显示错误消息的弹出窗口。 请让我知道如何创建一个通用方法并在服务块中调用它。就像我现在用“showErrorPage()”做的一样。

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'

@Injectable()
export class DataService {
    private reqData = {};
    private url: string;
    constructor(private http: Http) {
    }

    getResult(searchObject: {}): Observable<Response> {
        // some logic
        return this.http.post(<my url>, <data to be sent>)

        .map((response: Response) => {
            return response;
        })
        .catch((error: any) => {
            if (error.status === 302 || error.status === "302" ) {
                // do some thing
            }
            else {
              return Observable.throw(new Error(error.status));
            }
        });
    }
}

在我的组件中,我这样称呼它

import { Component,EventEmitter, Output, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
// importing DataService ';

@Component({
  selector: 'o-result',
  templateUrl: './o-result.component.html',
})

export class AComp implements OnInit {
    constructor(
        private dataService: DataService
    ){

    }

    ngOnInit() {
      this.dataService.getResult(<url>, <params>)
      .subscribe(
         response => {
             // doing logic with responce
         }
          ,
          error => {
            this.showErrorPage();
         }
      )

    }

    showErrorPage(): void {
      // displaying error in popup
    }
}

【问题讨论】:

    标签: angular angular2-services


    【解决方案1】:

    根据angular style guide

    数据管理的细节,例如标头、HTTP 方法、缓存、错误处理和重试逻辑,与组件和其他数据消费者无关。

    您的实现似乎是正确的。

    此外,http client 文档提供了相同的实现。

    【讨论】:

    • 感谢您的帮助!!
    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    相关资源
    最近更新 更多