gpt4 book ai didi

angular - Typescript - 空数组引用

转载 作者:搜寻专家 更新时间:2023-10-30 21:37:33 26 4
gpt4 key购买 nike

我正在用 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数组是空的,但是为什么??

最佳答案

考虑到 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
});

For more detail please follow // Execution Flow : #number , this way the whole execution flow will be executed

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
}

关于angular - Typescript - 空数组引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49004935/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com