Adding an element to an array does not automatically reflect on the user interface

After fetching JSON data from the endpoint, I am attempting to update an array but not seeing the expected results on the frontend.

export class LocationSectionComponent implements OnInit{


  myControl = new FormControl();
  options : string[] =  ['0089/PITT', '0085/CALI', '0090/MASS'];
  filteredOptions: Observable<string[]>;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      );

      this.fetchData();
  }

  private _filter(value: string): string[] {
        const filterValue = value.toLowerCase();
        return this.options.filter(option => option.toLowerCase().includes(value));
      }

   private fetchData ()
   {
   this.http.get('http://localhost:9090/api/v1/facility/1')
   .subscribe(responseData => {
    const facilityOrigin = responseData.facilityNumber +"/"+ responseData.name;
    this.options.push(facilityOrigin);
    console.log(this.options);
    });
   }

When calling the fetchData() method and performing a push operation, I get an updated array like this:

(4) ["0089/PITT", "0085/CALI", "0090/MASS", "89/PITT"]
0: "0089/PITT"
1: "0085/CALI"
2: "0090/MASS"
3: "89/PITT"
length: 4
__proto__: Array(0)

However, on the frontend, only 3 options are visible: ['0089/PITT', '0085/CALI', '0090/MASS']. How can I resolve this issue? Is it a scope problem or something else?

Answer №1

Give this a shot:

this.options = [...this.options];  // after adding new items

If your component has ChangeDetectionStrategy.OnPush set, you might want to consider calling this.cdr.detectChanges();

For more information, check out: onpush-change-detection-how-it-works

Answer №2

Consider using

this.options = this.options.concat(facilityOrigin);

in place of

this.options.push(facilityOrigin);

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

Exploring how process.argv in NodeJS can be utilized within JavaScript code compiled by

I'm having trouble compiling a basic TypeScript file using webpack (with 'awesome-typescript-loader') that needs to access command line arguments. It seems like the compiled JavaScript is causing a problem by overriding the Node 'proce ...

Building secure authentication with Angular, node.js, and an identity provider through SAML integration

Implementing SSO using SAML2 is my goal, but I am facing a challenge with a distributed system where each instance operates independently on its server. There are three instances in the environment: Instance #1: an angular frontend Instance #2: a node.js ...

The application's user interface is currently unable to access the REST API of the SSO Server

In the Angular front end, we are encountering an issue where it cannot call the REST API of the SSO server in the customer's environment to retrieve the open-id configuration. There doesn't seem to be any network calls being made when checked in ...

Update all occurrences of a particular value to null within the Realtime Database using Firebase Cloud Functions

I need to update the values of a specific userID linked to multiple post keys in my database by setting the userID to null. The userIDs are associated with post keys located in the path: posts/ivies/userIDs in my database. Take a look at how the database i ...

A new concept within the realm of programming is the Export class statement that utilizes

Is it possible to define both a class and an interface in the same file and export the class directly without any issues? I have encountered problems when using export default Foo, as it exports as { default: Foo } instead of the actual class object. I am ...

Are you looking to refresh the Amplify Redirect URL?

Is there a way to update the redirection URI for Amplify signout in the 'aws-exports' file? What steps should be taken to make this change? Can we simply modify the file directly and then execute 'amplify push'? Update After attempti ...

Steps for registering an Angular application on a Eureka server

I'm trying to integrate my Angular application with a Spring Cloud Eureka server. I came across the eureka-js-client library, but I'm unsure about where to place the configuration settings. Additionally, there are methods like client.start() and ...

Uploading audio mp3 files with Angular 2 and ExpressJS to the server (maximum size of 16MB)

I am embarking on a new project that will require users to upload audio MP3 files under 16MB in size, which falls within the maximum file size limit for mongoDB. I have been researching but haven't found a clear solution on how to handle this on the s ...

What is the best way to initiate multiple processes in Node.js and ensure they finish before proceeding?

When working with Node.js and TypeScript, my goal is to initiate multiple processes using the spawn function. Afterwards, I aim to ensure all of these processes are completed before proceeding to execute any additional commands. ...

The TypeScript factory design pattern is throwing an error stating that the property does not

While working with TypeScript, I encountered an issue when trying to implement the factory pattern. Specifically, I am unable to access child functions that do not exist in the super class without encountering a compiler error. Here is the structure of my ...

What is the best way to integrate qrcode-generator into an Angular 2 application?

I've been trying to implement the qrcode-generator in my app without success, even though it works in plunker. In my app, I am using angular-cli and angular 2.rc-1. Here are the steps to reproduce: ng new newAppName cd newAppName ng serve It work ...

I can't seem to catch my Zod error, even though 'express-async-errors' is already installed. What could be causing this issue?

I've been working on developing an API, but I'm facing issues with setting up a global error controller using Zod. It seems that the global error handler is not being called even though I'm using express-async-errors. Below is my error mana ...

Can the dimensions of a dialog be customized in Angular Material Design for Angular 5?

I am currently developing a login feature for an Angular 5 application. As part of this, I have implemented an Angular Material Design popup. Within the dialog screen, I have a specific process in place: The system checks the user's email to determi ...

Multiple Invocations of Angular Observable Service

I am facing an issue with my service method that returns an observable. In my component, I subscribe to this observable when it is loaded and have added a console.log in the service to track each time it is called. Upon running my application and checking ...

Generating a UTC timestamp in TypeScript

I am currently facing an issue with my application where I need to ensure that it always uses UTC time, regardless of the system time. I have a method in place to create a date: public static createDate(date: Date = new Date()): Date { return new Dat ...

What is the best way to prevent a font awesome icon from appearing in a span during data loading

I am currently working on an Angular 11 application where I have implemented an icon to trigger the loading of a graph. However, I have noticed that there is a delay in loading the graph when the icon is clicked. To prevent users from triggering the icon m ...

The ion-list will only load image URLs once the height has been established

I've been dealing with a technical issue that I don't have much experience in, and I'm struggling to find a solution. While I now understand the root cause of the problem, I am unsure how to resolve it. The webpage I am working on sends a r ...

Issue with Redis cache time-to-live not adhering to set expiration

I have encountered an issue while using IoRedis and DragonflyDB to implement rate limiting in my web application. Despite setting a TTL of 5 seconds for the keys in the Redis DB, sometimes they do not expire as expected. I am struggling to understand why t ...

Updating a URL parameter in Angular using programmatic methods

If I have a dynamic component that shows information about different characters in a story. Once a character is chosen, specific details will be displayed within the same component. The objective is to include both the story id and character id in the URL ...

What makes TypeScript believe that the variable could possibly be undefined when it is clearly not the case?

I recently encountered an issue where TypeScript incorrectly identifies a variable as possibly being undefined. Here is a simplified example: const func = (val1?: boolean, val2?: boolean) => { if (!val1 && !val2) return; let result: boolean; ...