【问题标题】:Get First Index in Array Object Type Scripts获取数组对象类型脚本中的第一个索引
【发布时间】:2019-10-19 19:26:37
【问题描述】:

我想在下面的代码 sn-p 中从数组对象 dataList 中获取索引零记录。我是 JavaScript 和 Typescript 的新手。

dataList: Array<any> = [];
 data: any;

 constructor(private apiService: ApiService) {  


   this.apiService.getEncounterDashBoard(this.searchCond)
     .subscribe(data => {
       this.dataList = data.result;
     });

    let labels = this.dataList[0];
}

【问题讨论】:

  • let labels = this.dataList[0]; 放在this.dataList = data.result; 之后。原因是dataList 在回调中异步更新,这意味着this.dataList[0] 在调用时可能不会保存任何数据。
  • .subscribe 是一个异步函数。您必须在 .subscribe 内设置 labels

标签: javascript arrays angular typescript ecmascript-6


【解决方案1】:

你可以这样试试

dataList: Array<any> = [];
 data: any;

 constructor(private apiService: ApiService) {  

 let labels = [];
   this.apiService.getEncounterDashBoard(this.searchCond)
     .subscribe(data => {
       this.dataList = data.result;
       labels = this.dataList[0]; 
// here you can see that we are access the data inside the subscription block bcs javascript is asynchronous. So it is not wait complete the api call 
     });
}

【讨论】:

  • 你应该在订阅块之外声明标签,否则只能在里面使用。
【解决方案2】:

将异步操作视为在其余操作之后发生的操作。 您的 getEncounterDashBoard 被调用并启动请求,但您的代码中的所有内容都会继续,无论是否有响应(通常没有响应,因为一切都太快了)。

因此,您的let labels 正试图在您真正得到回复之前获得this.dataList[0]。您可以做的一件事是创建一个组件范围的变量labels,然后在异步函数的回调中(在subscribe 内)分配它,这样会在异步函数解析后发生。

另一种选择是创建一个函数来处理您希望在解析异步后发生的逻辑,并在 subscribe 中调用它。

afterDataList() {
  let labels = this.dataList[0]
  // do something with it
  // ...
}

【讨论】:

    【解决方案3】:

    将线放在subscribe 函数内。

    .subscribe(data => {
       this.dataList = data.result;
       let labels = this.dataList[0];
     });
    

    你也可以使用 ES6 解构:

    .subscribe(data => {
       this.dataList = data.result;
       let [labels] = this.dataList;
     });
    

    【讨论】:

      猜你喜欢
      • 2023-01-23
      • 2018-06-06
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 2018-11-25
      • 1970-01-01
      • 2012-02-21
      相关资源
      最近更新 更多