首页 > 解决方案 > 满足端点响应的空响应

问题描述

我有一个订阅端点以获取响应的方法。我有一个端点返回 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我上面评论的那一行的错误。知道我能做些什么来避免这个错误吗?

标签: javascriptangulartypescript

解决方案


任何一个

  1. 添加一个条件来检查属性是否null在访问它之前(它将保留this.list其原始值):

    if (resp.loanAdjustmentResult != null) {
      this.list = resp.loanAdjustmentResult.loanAdjustmentList;
    }
    
  2. 使用可选的链接运算符(将保留this.listundefined):

    this.list = resp.loanAdjustmentResult?.loanAdjustmentList;
    

推荐阅读