寻找帮助来捕获Angular HttpClient获取请求中的HTTP错误,并将其传递回发起请求的组件,以便以对用户友好的方式处理错误。
我的Angular 7应用程序具有一个报告模块,我正在尝试为其添加错误处理。有一个组件report-list
在共享的reports
服务中使用changeReport()方法,该服务更新了reports-view
组件所订阅的可观察对象。 reports-view
获取更新的currentReport
(这是报告ID号)时,它将从服务器中获取具有指定报告ID的完整报告。
我在模拟此模块的客户端时遇到的问题是,我尝试获取的报告ID可能不存在,这是我应该能够处理的条件。理想情况下,我要更新报告视图,并显示一条错误消息“找不到报告ID”。我去研究了Angular文档中的catchError,在RxJS和HttpClient的指南部分以及HTTP教程中仅找到了其用法示例。搜索可观察对象和管道也无济于事。有谁知道我可以阅读的任何资源可以帮助我实现这一目标,和/或我需要阅读并理解哪些相关概念才能实现我正在尝试做的事情?
reports.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>())
);
}
reports-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;
});
}
}
reports-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错误)时会通知报表视图组件,以便我可以使用对用户友好的错误来适当地更新视图内容。
答案 0 :(得分:0)
我被定向到RxJS文档,显然是我可以找到关于catchError和observables的更多细节。