In Angular components, data cannot be updated without refreshing the page when using setInterval()

Here's the Angular component I'm working with:

export class UserListComponent implements OnInit, OnDestroy {
  private _subscriptions: Subscription;
  private _users: User[] = [];
  private _clickableUser: boolean = true;

  constructor(
    private route: ActivatedRoute,
  ) { }

  ngOnInit() {
    const source = interval(1000);
    const users = this.route.snapshot.data['users'] as IUserInterface[];

    this._subscriptions = source.subscribe(() => this._users = users.map(user => new User(user)))

  }

  ngOnDestroy() {
    this._subscriptions.unsubscribe();
  }

I am able to retrieve the data, but the interval isn't updating it without a page refresh.

Answer №1

ngOnInit() is a special lifecycle hook in Angular that runs only once when a component is initialized for the first time. This means that the active route is read only once, resulting in the users array always being the same.

If you want to update your component every time the route data changes, you should subscribe to this.route.data without using snapshot. Here's an example of how you can achieve this:

this._subscriptions = this.route.data.subscribe(data => this._users = data['users'].map(user => new User(user)));

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

When I try to alter HTML using JS, I encounter an undefined error related to AngularJS

Using this specific function: function adjustContent(elemento){ if (document.getElementById(elemento).innerHTML.indexOf('✔')>0){ document.getElementById(elemento).innerHTML=document.getElementById(eleme ...

Verify whether the initial value is distinct from the subsequent one using AJAX

I'm currently working on a project where I need to compare the first value received from an AJAX call to the subsequent values. However, I seem to be stuck and unable to figure out how to achieve this. Every 5 seconds, I am checking the follower count ...

Update a JQuery function for an input field following an innerHTML command

Using JQuery to check the file size and name from an html file input field can be a useful tool. The input field in question looks like this: <div id="uploadFile_div"> <input name="source" id="imageFile" type="file" style ="border: 1px solid ...

Calculate the total sum of selected values in a multiple select dropdown using jQuery

Is there a way to calculate the sum of selected items in a multiple selection dropdown menu? For instance, if I select "X12SO" and "X13SO", their values should add up to 30. let total = 0; $("select[name='myselect[]'] option").each(function(){ ...

Include a Class into a label using jQuery

I am having an issue where I need to specifically add the error class to a <label> with the name attribute set to choice_16_0. However, when I try to achieve this using my code, it ends up changing all labels on the page to <label for="choice_16_0 ...

Customizing Angular with SASS Theming

After coming across the query How can switchable themes be implemented in SCSS?, particularly the second response which drew inspiration from this insightful Medium post, I decided to try implementing themes using SASS on my project. Unfortunately, I hav ...

Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue: [ { "project_id": 1, "project_name": "CDP", "role": "PL" }, { "project_id": 2, "project_name": "Admincer", "role": "PM" }, I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific ...

The function socket.on(..) is not being triggered

Currently, I am in the process of developing a straightforward website to showcase socket communication and chat capabilities. The server side is coded using Python Flask app, while the client-side utilizes JavaScript. Below is an excerpt from the server c ...

Using Angular to create an Echarts timeline that showcases 3 distinct categories

Here is an example graph created with Highcharts Struggling to replicate a chart like this using Echarts and ngx-echarts. Has anyone encountered this issue before? Currently utilizing the following dependencies: "@angular/animations": "^17 ...

Discovering the bottom scroll position in an Angular application

I am working on implementing two buttons on an Angular web page that allow the user to quickly scroll to the top and bottom of the page. However, I want to address a scenario where if the user is already at the very top of the page, the "move up" button sh ...

Starting the selection process using AngularJS and ng-repeat

My challenge is to have a pre-filled option in a select-box using ng-repeat with AngularJS 1.1.5. However, the select box always starts off with nothing selected and an empty option, which I don't want. It seems to be a side effect of not having anyth ...

Perform an AJAX call from the main file after inserting data using AJAX beforehand

I am in need of assistance with a question I have. On a page, an AJAX function is executed after the page finishes loading, creating a table in PHP that contains two buttons: one for changing passwords and the other for deleting. This table is then injecte ...

What is the process for linking dynamic content to document-ready events?

When it comes to jQuery and JavaScript, I admittedly struggle a bit. I have a specific question but can't seem to find the right search terms to get me there. It involves using either .trigger() or on(), but I'm unsure of the correct implementati ...

What is the best way to showcase a value in JavaScript using CSS styling?

I'm looking to customize the background, font style, and outline for both open and closed elements in the code snippet below: a.innerHTML = "We are Open now now."; a.innerHTML = "We are Closed, arm."; Additionally, I want to appl ...

Interacting with the Follow/Unfollow button using jQuery/Ajax, managing repetitive actions efficiently

I'm working on developing a Follow/Unfollow button that can toggle between the two functions without requiring a page refresh. It currently works smoothly - when I click "Follow," it adds the follow data to the database and displays the "Unfollow" but ...

Randomize the array of images in Nuxt every time the page is reloaded to display a variety of logos in the carousel

I've set up a carousel of logos, with the intention to randomize their order every time the page reloads. The challenge is that my layout only allows for 10 images to be displayed at once. While it seems like everything is functioning correctly, I&ap ...

The Integration of Google Books API with Ajax Technology

When a user enters an ISBN number in the search box, it triggers a display of information from the Google Books API within a div. This information is fetched from a JSON file in the standard format and includes details like title, subtitle, author, and des ...

Callbacks for AJAX responses that are asynchronous

After using AJAX in a limited and straightforward manner for some time, I find myself currently debugging a web application that heavily relies on JavaScript and JQuery for client-side coding. One issue that has caught my attention is the possibility of mu ...

Choose does not showcase the updated value

My form contains a form control for currency selection Each currency object has the properties {id: string; symbol: string}; Upon initialization, the currency select component loops through an array of currencies; After meeting a specific condition, I need ...

Enhancing the type safety of TypeScript Generics

Uncertainty looms over me - am I committing an error, or is this all part of the plan... Within my academic domain class Collection<E> { ... } Lies a function public Insert(item: E): void { ... } I construct a specific instance of my list const ...