ค้นหาเว็บไซต์

angular - Typescript - การอ้างอิงอาร์เรย์เป็นค่า null


ฉันกำลังเขียนแอปพลิเคชันใน TypeScript/Angular และฉันมีบริการที่ดึง JSON พร้อมข้อมูล และฉันอยากจะแสดงวัตถุที่ดาวน์โหลดมา แต่สามารถเกิดขึ้นได้ว่าวัตถุอาจมีมากกว่าที่ฉันจะแสดงในคอมโพเนนต์ HTML หนึ่ง ดังนั้นฉันจึงควรแบ่งอาเรย์ของวัตถุเหล่านี้ อย่างไรก็ตามก่อนหน้านั้นฉันควรกรองวัตถุทั้งหมดจาก JSON ตามที่อยู่ IP ดังนั้นฉันจึงเขียนคอมโพเนนต์แบบนี้:

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) { }

}

แต่ฉันไม่สามารถใช้ฟังก์ชันการกรองได้เพราะอาร์เรย์ของพ็อดว่าง แต่ทำไมล่ะ??

คำตอบ #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
}