Angular 7错误通知不显示问题求助(已尝试临时方案)
你遇到的核心问题是错误格式不匹配:原代码里用throw throwError('NoDataError')抛出的是一个Observable实例,而不是HttpErrorResponse对象,导致processServerException里的res.error判断逻辑无法命中。
我们需要调整错误抛出的方式,确保错误流传递的是符合HttpErrorResponse格式的对象,同时修正RxJS管道里的逻辑问题:
1. 修正processReportResponse函数
保持你临时方案里的HttpErrorResponse抛出方式,补充完整参数让错误格式更标准:
processReportResponse(response: HttpResponse<any>) { if (response.status === 204) { // 抛出标准HttpErrorResponse,确保和后端返回的错误格式一致 throw new HttpErrorResponse({ error: 'NoDataError', status: 204, statusText: 'No Content', url: response.url }); } else { return new Blob([response.body], { type: 'application/pdf' }); } }
2. 修正getOrganizationUsersSalesReport的RxJS管道
原代码里的map操作符缺少返回值,而且URL拼接可以更简洁,调整后:
getOrganizationUsersSalesReport(from: Date, to: Date, userIds: string[]): Observable<any> { const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; const url = `${this.url}userSales?from=${from.getTime()}&to=${to.getTime()}&timezone=${timezone}&userIds=${userIds.join(',')}`; return this.http.get(url, { observe: 'response', responseType: 'blob' }) .pipe( map(res => this.processReportResponse(res)) ); }
这里的关键优化:
- 用模板字符串简化URL拼接,可读性更强
userIds直接用join(',')替代冗余的map操作map操作符正确返回processReportResponse的结果,抛出的错误会自动进入Observable的错误流
3. 验证processServerException逻辑
现在错误流传递的是标准HttpErrorResponse对象,你的现有逻辑可以正常触发通知:
processServerException(res: HttpErrorResponse) { console.log(res); this.stopLoading(); if (res.error === 'NoDataError') { this.alertService.info(this.translateService.instant('reporting.nodata')); } }
你用throw new HttpErrorResponse(...)的思路完全正确,因为processServerException期望接收的是HttpErrorResponse类型的错误对象,而不是throwError返回的Observable。直接抛出HttpErrorResponse会让RxJS自动将其转为错误流的参数,完美匹配你组件里的错误判断逻辑。
而原代码里throw throwError('NoDataError')的错误在于:throwError是用来创建发射错误的Observable的函数,你直接throw这个函数的返回值,相当于抛出了一个Observable对象,而非错误内容,所以res.error自然无法匹配。
内容的提问来源于stack exchange,提问作者Patrik Alexits

