Why is there a delay in updating my front-end Angular data when making changes from the API? I have to refresh the page for the data to be updated instantly

Why is my front-end Angular data not updating instantly when I update the roomList from the API? The API is functioning correctly and the results are being updated, but I have to refresh the page for the changes to show. As a newcomer to Angular, I am struggling to figure out how to solve this issue. I am working with Angular version 17.

This code snippet can be found in my room.component.ts file:

update() {
  const extraRoom: RoomList = {
    roomNumber:2,
    roomType: 'tory',
    amenities: 'Gas,CoolerKitchen',
    price: 300,
    photos: 'https://imagfine.jpg',
    checkinTime: '17-09-2002',
    checkoutTime: '02-Nov-2021',
    rating: 1,
   
  };
  this.roomsService.updateRooms(extraRoom.roomNumber,extraRoom).subscribe((data)=>{const idx=data.roomNumber;
 this.roomList.forEach((value,index)=>{
//  this.updateArray(data);
// this.roomList.push(extraRoom);
this.roomList[data.roomNumber].roomType =data.roomType;
this.roomList[data.roomNumber].amenities= data.amenities;
this.roomList[data.roomNumber].price =data.price;
this.roomList[data.roomNumber].photos = data.photos;
this.roomList[data.roomNumber].checkinTime = data.checkinTime;
this.roomList[data.roomNumber].checkoutTime = data.checkoutTime;
this.roomList[data.roomNumber].rating = data.rating;
 });

The service file responsible for handling updates looks like this:

 updateRooms(id:number,room:RoomList){
    return this.http.put<RoomList>(`/api/hotel/${id}`,room);
  }

Despite my expectations of immediate data updates upon clicking the edit button, the changes only appear after I manually refresh the page. This behavior is not what I intended, and it's hindering the user experience.

This section relates to my rooms.component.ts file:

import {
  AfterViewChecked,
  AfterViewInit,
  Component,
  DoCheck,
  OnInit,
  QueryList,
  SkipSelf,
  ViewChild,
  ViewChildren,
} from '@angular/core';
import { Room, RoomList } from './rooms';
import { CommonModule } from '@angular/common';
import { RoomsListComponent } from '../rooms-list/rooms-list.component';
import { HeaderComponent } from '../header/header.component';
import { RoomsService } from './services/rooms.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'hinv-rooms',
  standalone: true,
  templateUrl: './rooms.component.html',
  styleUrl: './rooms.component.scss',
  imports: [CommonModule, RoomsListComponent, HeaderComponent],
})
export class RoomsComponent
  implements DoCheck, OnInit, AfterViewInit, AfterViewChecked
{
  // Room component logic here
}
[![This image showcases the appearance of my frontend](https://i.sstatic.net/eImmJ.png)](https://i.sstatic.net/eImmJ.png)

Answer №1

Consider implementing two-way binding for real-time frontend data updates when the variable changes, using [(ngModel)]. Reach out if you need further details or encounter any issues.

Answer №2

After making changes to roomList, it appears that your view is not being updated.

this.roomsService.updateRooms(extraRoom.roomNumber, extraRoom).subscribe( … 

It seems like there might be a change detector issue where Angular is not running change detection.

One solution is to manually call ChangeDetectorRef when subscribing to the observable.

To force a re-render of your view, use this.cd.detectChanges() after fetching new data.

The detectChanges method triggers change detection on the component and prompts an update.

Consider trying the following:

constructor(…, private cd: ChangeDetectorRef) {}


this.roomsService.updateRooms(extraRoom.roomNumber, extraRoom).subscribe((data)=>{

   const idx = data.roomNumber;

   this.roomList.forEach((value, index)=>{
    // this.updateArray(data);
    // this.roomList.push(extraRoom);

    this.roomList[data.roomNumber].roomType = data.roomType;
    this.roomList[data.roomNumber].amenities= data.amenities;
    this.roomList[data.roomNumber].price = data.price;
    this.roomList[data.roomNumber].photos = data.photos;
    this.roomList[data.roomNumber].checkinTime = data.checkinTime;
    this.roomList[data.roomNumber].checkoutTime = data.checkoutTime;
    this.roomList[data.roomNumber].rating = data.rating;
   });

   this.cd.detectChanges();

});

Alternatively, you can update without using forEach:

 ..
const indexToUpdate = this.roomList.findIndex(item => item.roomNumber === data.roomNumber);
this.roomList[indexToUpdate] = data;
 ..

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

manipulator route in Nest.js

I have the following PATCH request: http://localhost:3000/tasks/566-344334-3321/status. The handler for this request is written as: @Patch('/:id/status') updateTaskStatus() { // implementation here return "got through"; } I am struggling t ...

The behavior in Angular where updates to arrays in child components do not reflect the data passed from the parent is known as "

My child component is not listening for changes in data from the parent when using ArrayObjectParser. Any ideas on how to fix this issue? Please assist me. import { Component, OnInit, Inject, ViewChild, Input } from '@angular/core'; import { Form ...

Developing a barrel component in React (utilizing .tsx)

My current directory structure looks like this: src assets components models counter.tsx index.ts The code found inside models/index.ts (also known as the barrel file) export * from "./counter"; The code within models/counter.ts export default in ...

Even as I create fresh references, my JavaScript array object continues to overwrite previous objects

Coming from a background in c# and c++, I am facing some confusion with a particular situation. Within the scope of my function, I am creating a new object before pushing it into an 'array'. Strangely, when I create the new object, it appears to ...

Troubleshooting: The issue of ngModel being undefined in Angular2 with the <input> element

I am currently working with Angular2 and a modified version of Semantic-UI that includes a calendar module. I am utilizing the `calendar` and `dropdown` functionalities: constructor() { setTimeout(() => { jQuery('.ui.dropdown').dr ...

Create a function in JavaScript that is able to accept a variable number of objects as arguments

I have a good grasp of how to pass infinite parameters in a function in JavaScript. But what about accepting any number of objects as parameters in a function? This is my current implementation: function merge<T>(objA: T, objB: T){ return Object. ...

Helping React and MUI components become mobile responsive - Seeking guidance to make it happen

My React component uses Material-UI (MUI) and I'm working on making it mobile responsive. Here's how it looks currently: https://i.sstatic.net/kxsSD.png But this is the look I want to achieve: https://i.sstatic.net/kJC2m.png Below is the code ...

I'm puzzled as to why my object remains static even after I reassign properties within a forEach loop

When retrieving an array of objects from an RX/JS call through an http backend, I encounter a peculiar issue. After making modifications to the object within a loop (attempting different methods like .forEach), the values seem to change temporarily but rev ...

Is there any benefit to me verifying for Zone?

I have a custom function that allows me to execute another function within an Angular zone, regardless of whether it was called from outside of Angular. Check out my implementation: export class MyZones { public static maybe(zone: NgZone, callee: () ...

Exploring Typescript ENUMs

I need to save a list of alpha-numeric options as an ENUM in Typescript. Here is an example list: 1.134/2394 x 3-xyz 2.123/234 y 3-ery 3.345/99 t 4-red 4.4.1hv 3 secondary 5.2.51hv 3 secondary 6.1.61hv 3 secondary If anyone has thoughts on how to ...

Issue with assigning objects to an array

I'm currently working on a TypeScript application and I've run into an issue with assigning values. Here are the interfaces for reference: export interface SearchTexts { SearchText: SearchText[]; } export interface SearchText { Value: st ...

Creating a modal dialog using a function in a TypeScript file

Hey there, fellow developers! I have a question that might seem simple. So, in my HTML code I've got a Modal Dialog that pops up using ng2 Bootstrap. It's working fine, but... I want to replace this line of code "<button class="btn btn-prim ...

Display the customer's name using the Mat-Select display object property by fetching it from the previously selected or saved value

Having some difficulties with mat-select and options in my Angular 6 project. Here is the scenario I am facing: I would like to create a dropdown list of organizations where I can select one and save the complete organization object, not just its name. ...

Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined. interface JSON { stringify(value: any, /*...*/): undefined; } However, executing JSON.stringif ...

The process of extracting values from an HTML tag using Angular interpolation

I am working on an Angular application that has the following code structure: <p>{{item.content}}</p> The content displayed includes text mixed with an <a> tag containing various attributes like this: <p>You can find the content ...

Is there a way to replicate the tree structure of an array of objects into a different one while modifying the copied attributes?

Is there a way to replicate the tree structure of an array of objects to another one in TypeScript, with different or fewer attributes on the cloned version? Here's an example: [ { "name":"root_1", "extradata&qu ...

Unable to apply 3rd condition with ngClass into effect

I've been attempting to incorporate a third condition into my ngClass. Initially, I managed to get two classes working in my ngClass to change the row colors alternately. [ngClass]="{ totalrow:i%2 != 0, odd:i%2 == 0}" Now, I'm trying to introdu ...

Is there a pipe operator available that executes code prior to resolving a subscription, such as making an HTTP call?

When making HTTP calls, I want to include a loading indicator before the call is made. Currently, my code looks like this: this.loadingIndicatorService.setLoadingIndicatorOn(true) this.cop.getunMappedTechnologyDetails().pipe( finalize(() => { ...

Trigger Screen Reader to Announce When a Component Is Deleted

When the last filter item is removed, I want the screen reader to announce "All Filters Are Removed." However, if the active filter component is removed without any other element to assign an aria-label attribute, I'm not sure how to handle this situa ...

Wrapping an anonymous function in a wrapper function in Typescript can prevent the inferred typing

I am encountering an issue with typing while coding: function identity<T>(v: T): T{ return v; } function execute(fn: {(n: number):string}) {} execute((n) => { // type of n is 'number' return n.toFixed(); }) execute(identity(( ...