Angular请求无数据库数据时返回404,如何实现无数据不报错?
解决方案
该问题的核心原因是后端接口在查询结果为空时返回了404状态码,而非正常的200响应+空数据集,你可以选择以下任意一种方案处理:
方案1:调整后端接口(最优解)
- 修改后端接口返回逻辑:匹配数据为空时不返回404状态码,统一返回200状态码,响应体结构和有数据时保持一致,仅将
items字段设置为空数组即可。该方案符合REST接口设计规范,且前端无需修改任何现有代码即可适配空数据场景。
方案2:前端兼容处理(无法调整后端时使用)
直接修改前端代码,在错误回调中判断状态码,对404错误做特殊处理,不触发错误提示,直接按空结果逻辑执行,修改后的代码如下:
private _pageEventDealsForApprovalList() { this.searchInput = ''; const status = 'ForApproval' this.isLoading = true; this.dealService .getAllDeals( status, this.accountId, this.transaction.id, this.table.pageIndex + 1, this.table.pageSize, this.searchInput, this.table.sortParams, this.table.sortDirs ) .pipe(finalize(() => (this.isLoading = false))) .subscribe({ error: (err) => { // 404状态按空结果处理,不弹出错误 if(err.status === 404) { this.table.data = []; this.todalDealsForApproval = 0; setTimeout(() => { this.trasactionService.transactionEvent.next({ sendData: this.todalDealsForApproval, operation: 'transaction/update/count' }); }, 1000); return; } // 非404的其他错误正常弹出提示 this.notificationService.showError(err); }, next: (res) => { this.table.data = res.items; this.todalDealsForApproval = res.items.length; setTimeout(() => { this.trasactionService.transactionEvent.next({ sendData: this.todalDealsForApproval, operation: 'transaction/update/count' }); }, 1000); }, complete: noop, }); }
可选优化
如果想简化代码避免重复逻辑,也可以在RxJS的管道中提前处理404错误:
// 在pipe中新增catchError操作符 .pipe( catchError((err) => { if(err.status === 404) { // 将404转为空结果的正常响应 return of({ items: [] }); } // 其他错误继续抛出 return throwError(() => err); }), finalize(() => (this.isLoading = false)) )
修改后error回调只需要处理非404的错误即可,next回调的逻辑不需要做任何调整。
内容的提问来源于stack exchange,提问作者Rajiv Kumar
相关产品推荐
相关产品推荐

