gpt4 book ai didi

angular - 使用 catchError 更新组件

转载 作者:行者123 更新时间:2023-12-03 08:46:02 25 4
gpt4 key购买 nike

寻求帮助在 Angular HttpClient 获取请求中捕获 HTTP 错误,并将其传递回发起请求的组件,以便以消费者友好的方式处理错误。

我的 Angular 7 应用程序有一个报告模块,我正在尝试为其添加错误处理。有一个组件report-list在共享 reports 中使用 changeReport() 方法服务,它更新了 reports-view 的 observable组件订阅。当reports-view获得更新的 currentReport (这是一个报告 ID 号),它使用指定的报告 ID 从服务器获取完整的报告。

我在模拟此模块的客户端时遇到的问题是我尝试获取的报告 ID 可能不存在,这是我应该能够处理的情况。理想情况下,我想用“找不到报告 ID”的错误来更新报告 View 。我在 Angular 文档中研究了 catchError,仅在 RxJS 和 HttpClient 的指南部分以及 HTTP 的教程中找到了它的使用示例。搜索 observables 和管道也没有多大帮助。有谁知道我可以阅读的任何资源可以帮助我实现这个目标,和/或我需要阅读和理解哪些相关概念才能实现我正在尝试做的事情?

报告.service.ts:

export class ReportsService {

private reportsUrl = 'api/reports';

/// Establishes the observable used to subscribe to which report to get
reportSelectionNum: number;
private reportSelection = new BehaviorSubject<number>(this.reportSelectionNum);
currentReport = this.reportSelection.asObservable();

constructor(private http: HttpClient) { }

/// Allows sibling component to update report
changeReport(reportID: number) {
this.reportSelection.next(reportID);
}

getReport(id: number): Observable<Report> {
const url = `${this.reportsUrl}/${id}`;
return this.http.get<Report>(url).pipe(
tap(_ => this.log(`getReport(${id})`)),
catchError(this.handleError<Report>())
);
}

报告-view.component.ts
export class ReportsViewComponent implements OnInit {

report: Report;

reportHeaders: string[];
reportData: Array<string[]>;

constructor(private reportsService: ReportsService) { }

ngOnInit() {
this.reportsService.currentReport.subscribe(report => {
if (report) {
this.getReport(report);
}
});
}

getReport(id: number): void {
this.reportsService.getReport(id).subscribe(report => {
this.report = report;
this.reportHeaders = this.report.data.shift();
this.reportData = this.report.data;
});
}
}

报告-list.component.ts
export class ReportListComponent implements OnInit {

reports: Report[];

constructor(private reportsService: ReportsService) { }

ngOnInit() {
this.getReports();
}

getReports(): void {
this.reportsService.getReports().subscribe(reports => this.reports = reports);
}

setReportID(id: number): void {
this.reportsService.changeReport(id);
}

}

我希望当发生特定类型的错误(例如 404 错误)时,报告 View 组件会收到通知,以便我可以使用对消费者友好的错误适本地更新 View 内容。

最佳答案

我被引导到 RxJS 文档,显然我可以找到有关 catchError 和 observables 的更多详细信息。

关于angular - 使用 catchError 更新组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54011150/

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