gpt4 book ai didi

angular - Angular2 中处理错误的最佳实践

转载 作者:太空狗 更新时间:2023-10-29 16:50:18 28 4
gpt4 key购买 nike

您好,我正在尝试接收从 catch block (服务)发送的错误。在多个组件中,我需要显示一个弹出窗口,其中显示错误消息。请让我知道如何创建通用方法并在服务 block 中调用它。就像我现在使用“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 style guide

The details of data management, such as headers, HTTP methods, caching, error handling, and retry logic, are irrelevant to components and other data consumers.

您的实现似乎是正确的。

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

关于angular - Angular2 中处理错误的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41998222/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com