Typescript - dealing with a null array reference

Currently, I am working on developing an application using typescript/angular. In this project, I have a service that retrieves JSON data and I want to display these downloaded objects. However, there is a possibility that the number of objects retrieved may exceed what can be displayed in a single HTML component. Therefore, I need to split this array of objects. Additionally, before doing so, I need to filter all the objects by IP address. To handle this scenario, I created a component like the one below:

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

}

However, I am facing an issue where the filtering function is not able to access the pods array because it is empty. This has left me wondering why the array is empty in the first place.

Answer №1

Due to the asynchronous nature of the code, your implementation should be as follows:

this.httpService.getPods().subscribe(data => {
    this.pods = data.items;
    console.log('Retrieved pods count: ' + this.pods.length); // include it here
    this.filtering(); // call the function from this point
});

For a more detailed explanation, refer to // Execution Flow : #number notation for complete execution flow.

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

// Execution Flow : 5
filtering() {
    console.log('Address count of Node_s: ' + this.node_s.status.addresses[1].address);
    console.log('Total Pod count: ' + 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
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript's contravariant object values

Here is an example of an overloaded Typescript function: function clearField(o : Record<"field", string>, nullify : false) : void function clearField(o : Record<"field", string | null>, nullify : true) : void function clearF ...

Attempting to call a function with a template variable is not allowed

@Component({ selector: 'modal', ... }) export class SimpleModal { modalOpen: boolean; isModalOpen(): boolean { return this.modalOpen; } } <modal #modalRef> <div *ngIf="modalRef.isModalOpen()">...</div> </mo ...

Dealing with permission-based errors on the interface

I've been working on implementing authorization in my Angular project for hours now, following this example. I have created an HTTP interceptor to handle errors, but I'm unsure how to display these errors in my login view. I have tried passing a ...

Transform the header elements into clickable links

How can I prevent the header items from acting as links when I right-click on them? Here is my code: (I don't want them to open in another window when right-clicked.) [![enter image description here][1]][1] ...

Is there a problem with Angular2 using TypeScript?

Currently, I am in the process of setting up my machine for Angular development by following the guidelines provided on https://angular.io/docs/ts/latest/quickstart.html As I proceeded to run "npm start" to launch my site, I encountered an issue with the ...

Should I implement jquery within angular 2, or opt for the current css/js frameworks available?

Embarking on the development of a website with Angular 2, my deadline is set within a month. I need to select a CSS/JS framework that seamlessly integrates with Angular 2. While using jQuery within Angular 2 is discouraged, I am curious if there are altern ...

Optimizing Performance in Firebase Cloud Functions - Defining Functions for Efficiency

Currently, I am organizing the code in my index.ts by creating simple line function definitions like: HTTP Example export const demoHttpApp = functions.https.onRequest( (req, resp) => new DemoHttpClass(req, resp).run() ); Real-Time Database Example ...

The 'import.meta' meta-property can only be used with the '--module' set to 'es2020', 'esnext', or 'system'.ts(1343)

Whenever I attempt to utilize import.meta.url (as demonstrated in the Parcel docs), I am consistently met with the error message "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es ...

What is preventing me from sorting multiple times?

My current challenge involves sorting an array of data multiple times for different purposes. While I could choose to save the sorted data on the back end, I prefer handling it this way. However, I have encountered a problem where only one sort operation ...

Creating HTML content from a function return in Angular

I'm trying to figure out the process through which TypeScript and HTML exchange data. (TypeScript) public getContactByTradingPartnerId(tradingPartnerId: number):string { const map = { 1001 : "<a href="/cdn-cgi/l/email-protection ...

Is it possible to utilize a variable within the 'has-text()' function during playwright testing?

With Playwright, I am attempting to locate an element based on the value of a variable For instance: let username = 'Sully' await page.click(`li:has-text(${username})`) However, I encounter the following error: page.click: Error: "has-tex ...

The entire space should be filled with the background

My goal is to achieve the following while addressing some current issues: The background is currently limited to affecting only the container. I want it to span the entire area. There needs to be space between the cards and padding inside them. https://i ...

Incorporate PrimeNG into an Angular2 application with the help of Webpack

I've been trying to integrate PrimeNG into my Angular2 application bundled with Webpack. To start, I executed the following npm commands: npm install primeng --save npm install primeui --save This updated my package.json with the following entries: ...

What is the best way to extract values from a specific table column and store them in an array using Angular?

I have a section of code containing a table in my component: expect-next-month.component.html <table id="users"> <tr> <th>Number of month</th> <th>Total checking e ...

"An identifier was expected causing a parsing error" triggered by v-on:change

Encountered an issue where importing a class to be used solely as a typescript type annotation resulted in a no-unused vars error. Following advice from this discussion thread, I added "plugin:@typescript-eslint/recommended" to the eslint config, ...

Guide to incorporating Bootstrap icons into an Angular application through programming techniques

Have you checked out the official bootstrap documentation for information on how to use their icons? https://i.stack.imgur.com/N4z2R.png I'm currently trying to understand the package and its usage. However, none of the options in the documentation ...

Encountering the error "Object potentially undefined" while attempting to activate Cloud Function during document creation

My goal is to automatically create a new authenticated user whenever a new document is added to the "users" collection. The necessary user details will be extracted from the fields "email" and "phone" in the new document. The challenge I am facing is that ...

Creating a dynamic dropdown using *ngFor

I have successfully implemented a dynamic dropdown feature based on response using *ngFor Response Data Array(3) 0: val_id:1 role_id:1 id:1 is_optional:false is_text:false 1: val_id:1 ...

Is it possible to utilize TypeScript version 2.0.6 in conjunction with Visual Studio 2017?

Is it possible to utilize TypeScript 2.0.6 with Visual Studio 2017, or do I need to use a version greater than 2.1? Also, can you explain the difference between Microsoft.TypeScript.Compiler and Microsoft.TypeScript.MSBuild? If I don't have Microsof ...

What could be causing the need for RxJs TypeScript files to be requested exclusively when my website is hosted on IIS?

When I develop my site using Visual Studio / IIS Express, everything runs smoothly without any unusual requests or 404 errors. However, once I publish the site to IIS and try to run it, I start receiving multiple requests for typescript files (.ts), prima ...