【问题标题】:Typescript - null array reference打字稿 - 空数组引用
【发布时间】:2018-08-06 21:06:16
【问题描述】:

我正在使用 typescript/angular 编写应用程序,并且我有一项服务可以获取带有数据的 json,并且我想显示这个下载对象,但可能会发生对象可能比我在一个 html 组件中显示的更多所以我应该拆分这个对象数组。顺便说一句,在此之前我应该​​通过 ip 地址过滤来自 json 的所有对象,所以我编写这样的组件:

export class ServerBoxComponent implements OnInit {

  pods = new Array<Pod>();

  @Input() node_s: NodeServer;

  getPods() {
    // console.log('Download pods');
    this.httpService.getPods().subscribe(data => {
      this.pods = data.items;
    });
    console.log('Download status: ' + this.pods.length);
  }

  filtering() {
    console.log('Node_s length: ' + this.node_s.status.addresses[1].address);
    console.log('Node_s length: ' + this.pods.length);
    for (let i = 0; i < this.pods.length; i++) {
      if (this.node_s.status.addresses[0].address === this.pods[i].status.hostIP) {
        console.log(this.pods[i].metadata.name);
        // this.node_s.podArray.push(this.pods[i]);
      }
    }
  }

  ngOnInit() {
    this.getPods();
    // this.filtering();
  }

  constructor(private httpService: HttpService) { }

}

但是我不能使用过滤功能,因为 pods 数组是空的,但是为什么呢??

【问题讨论】:

  • 当您调用this.getPods(); 时,pods 数组最终将被填充。如果您在 getPods() 填充数组之前调用您的 filtering(),它将为空
  • 它是异步执行的。 this.filtering() 在 this.getPods() 完成之前被执行。异步操作正在运行!使用 Promise 按顺序执行这些功能。

标签: angular typescript service ngoninit


【解决方案1】:

由于async 的行为,您的代码应如下所示:

this.httpService.getPods().subscribe(data => {
    this.pods = data.items;
    console.log('Download status: ' + this.pods.length); // call it here
    this.filtering(); // function should be called from here
});

更多详情请关注// Execution Flow : #number,这样 整个执行流程都会被执行

getPods() {
    // Execution Flow : 2
    this.httpService.getPods().subscribe(data => { 
        this.pods = data.items; // Execution Flow : 6
    });
    console.log('Download status: ' + this.pods.length); // Execution Flow : 3
}

// Execution Flow : 5
filtering() {
    console.log('Node_s length: ' + this.node_s.status.addresses[1].address);
    console.log('Node_s length: ' + this.pods.length);
    for (let i = 0; i < this.pods.length; i++) {
        if (this.node_s.status.addresses[0].address === this.pods[i].status.hostIP) {
            console.log(this.pods[i].metadata.name);
            // this.node_s.podArray.push(this.pods[i]);
        }
    }
}

ngOnInit() {
    this.getPods(); // Execution Flow : 1
    this.filtering(); // Execution Flow : 4
}

【讨论】:

  • 好的,它可以工作,但现在我有另一个问题,当我尝试将此过滤对象推送到数组时,出现如下错误:错误类型错误:无法获取未定义或空的属性“推送”参考
  • 该错误意味着您没有将任何内容推入阵列。您正在尝试推送 Null 值。
  • @AdKossa ,您只需要初始化要在其中推送数据的数组,您必须只是声明数组而不是初始化它
猜你喜欢
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 2017-09-28
  • 2020-08-18
  • 2020-04-24
  • 1970-01-01
  • 2016-11-01
  • 2020-11-29
相关资源
最近更新 更多