Search code examples
angulartypescriptservicengoninit

Typescript - null array reference


I'm writting application in typescript/angular and i have a service which get json with data and i'd like to display this downoad objects, but it can occur that objects can be more than i can display in one html component so i should split this array of objects. By the way before that i should filtering all objects from json by ip address, so i write component like that:

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

}

but i can't use filtering function because the pods array is empty, but why??


Solution

  • Coz of the async behaviour, Your code should look like this:

    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
    }