javascript - 满足端点响应的空响应
问题描述
我有一个订阅端点以获取响应的方法。我有一个端点返回 null 的情况,我正在尝试为此添加一个检查。
public list: Array<any>;
this.GetList(this.getListRequest)
.subscribe(
(resp) => {
this.progressSpinnerService.stopLoading();
this.list = resp.loanAdjustmentResult.loanAdjustmentList; //error is here
},
(error) => {
this.progressSpinnerService.stopLoading();
this.handleServiceError(error); // error handling.
this.serviceError = true;
}
);
服务响应如下所示
{
"header":{
"statuscode":"0",
"userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
"wfpt":null,
"paginationContext":null,
"reasonCode":null
},
"accountNumber":null,
"loanAdjustmentResult":null
}
我得到的错误是TypeError: Cannot read property 'loanAdjustmentList' of null
我上面评论的那一行的错误。知道我能做些什么来避免这个错误吗?
解决方案
任何一个
添加一个条件来检查属性是否
null
在访问它之前(它将保留this.list
其原始值):if (resp.loanAdjustmentResult != null) { this.list = resp.loanAdjustmentResult.loanAdjustmentList; }
使用可选的链接运算符(将保留
this.list
为undefined
):this.list = resp.loanAdjustmentResult?.loanAdjustmentList;
推荐阅读
- docker - Docker 容器中的别名命令不起作用
- php - 如何修复重复功能 ACF
- php - 贝宝 REST API 命名空间
- java - 第二种形式的代码没有运行?Java 表单
- mysql - 我如何计算订单数量,然后使用 SQL 中的 case 语句对它们进行分组
- batch-file - 如何在 Windows 上使用命令行创建多个具有不同扩展名的文件?
- sql - 为列中的每个唯一值附加行?
- r - 一个列中的两个条件和另一列中的另一个条件以在 R 中创建一个新列
- kubernetes - Grafana 变量查询未从 Prometheus pod 目标中检索所有端点(但获取其中一些端点)
- java - Vavr - 根据字段将 2 个 io.vavr.collection.List 类型的列表附加到单个列表中