The Array instance does not reflect changes made by the HTTP service request

Currently, I am tackling a situation where I must retrieve a series of objects from Spring Boot by making REST calls and then display them in the user interface using Angular 5.

This is what my component looks like:

export class BusinessComponent implements OnInit {

  serviceSavings:Services[] = [];

  constructor(private ServicesService:ServicesService) {
  }

  ngOnInit() {
    this.ServicesService.getServicesByCatID(PRODUCTSAVINGSID)
      .subscribe(serviceSavings => this.serviceSavings = serviceSavings);

    console.log("The length of serviceSavings :", this.serviceSavings.length); //this always prints zero.
  }

  examplemethod() {
    console.log("The length of serviceSavings :", this.serviceSavings.length);
  }
}

Currently, the issue lies with the log statement inside the init() method displaying 0 rows of the service. My goal is to retrieve each service from the list and perform actions on them.

Interestingly, when I move the same log statement to a user-defined method, triggering it with a user action in the UI, it accurately displays the count of the list as stored in the database table.

During the application load, I need to embed some business logic within init() to showcase certain values in the UI. However, the length of the retrieved list is consistently 0 in init(), making it impossible to iterate through the values. I suspect there is an issue with the update of the array object.

Here is what my service method looks like:

  getServicesByCatID(categoryid){
    return this.http.get(this.getServiceUrlByCategory(categoryid))
      .map(res => res.json());
  }

The Spring Boot application flawlessly returns the list of objects without any hitches at the backend.

Would appreciate any help in pinpointing the issue. Thank you.

Answer №1

Relocate your console statement within the subscribe() function.

ngOnInit(){

this.ServicesService.getServicesByCatID(PRODUCTSAVINGSID) 
.subscribe(serviceSavings => {
  this.serviceSavings = serviceSavings

  console.log("The length of serviceSavings :", this.serviceSavings.length)

});

}

Answer №2

In order to ensure you receive the result after the subscription is complete, it is advisable to move the retrieval inside the subscribe method. Additionally, if you intend to display this data in the view, consider using the async Pipe:

export class BusinessComponent implements OnInit {
 serviceSavings : Observable<Services[]>;

constructor(private ServicesService: ServicesService){}

ngOnInit(){
 this.serviceSavings = 
  this.ServicesService.getServicesByCatID(PRODUCTSAVINGSID); 
}

Then, you can loop through the data in the view as follows:

<p *ngFor='let service of serviceSavings | async'></p> 

Answer №3

After encountering a similar issue, I found that it is more effective to use the following code snippet:

 this.ServicesService.getServicesByCatID(PRODUCTSAVINGSID)
 .subscribe(serviceSavings => this.serviceSavings = [...serviceSavings]);

Rather than simply assigning

this.serviceSavings = serviceSavings
, it is advisable to use
this.serviceSavings = [...serviceSavings, newServiceSaving]
for adding elements to an array instead of .push(newServiceSaving)

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

I have a component that I utilized for subscription purposes. After subscribing to the method, I ensured to properly unsubscribe in order to prevent any memory leaks

Access code for services private postsData: Post[] = []; private updatedPosts = new Subject<Post[]>(); getPosts() { return [...this.postsData]; } getUpdatedPostsListener() { return this.updatedPosts.asObservable(); } addNe ...

Images in Angular Firebase causing scroll problems in Chrome

In regard to Angular 6, a common issue arises with slow image loading specifically in Chrome, not other browsers. The project utilizes Firebase and the snapshotchange method to fetch images for the Angular project. Image URLs used are like this: . The iss ...

422 Update Error when making changes in the modal using axios.put [laravel and vuejs 3]

I am currently working on a project using Laravel and VueJS 3, For updating details of a single user in a table row via a modal, I am utilizing the axios.put method. However, I am encountering issues when trying to submit the form inside the modal using a ...

Optimizing AngularJS performance with REST service caching

My AngularJS application requires caching of REST service responses, and I've come across libraries like angular-cached-resource that store data in the local browser storage. However, there are times when certain cached responses need to be deleted d ...

When using AWS/Cognito and setting up a user pool with CDK, is there a way to specify the character limits for standard attributes? Specifically, I would like to establish a minimum and maximum

When setting up a user pool in AWS/Cognito using CDK, how can I specify the string length for standard attributes? I've been trying to figure this out but haven't had any luck so far. I'm working with Typescript. This is how my user pool i ...

Using a file readStream within a post handler with Node.js, Request, and Express

Currently, I am utilizing nodejs and express4 for my development tasks. I am facing an issue with a form that has a post method for uploading files as base64, which I am then saving to a gridfs using streams. Below is the code snippet I am working with: ...

Utilize a dynamically defined union type to create a versatile callback function

I'm currently working on creating a message subscription function. A basic version without types is shown below: function createMessage(message) { postMessage(message) } function addSubscriber(messageType, callback) { handleNewMessage(message =&g ...

Having difficulty integrating requireJS and Node's Require in a single TypeScript project

I currently have a TypeScript project that is intended to work with both Node and the browser. In some scripts, I'm utilizing Node's require(), while in others requireJS's require(). The structure of my project directory is as follows: myPr ...

Issue of Angular lazy loading not functioning with query parameters

Need help with implementing lazy loading using query parameters. I have a reactive search form where for each post, I want to load a lazy module that displays the search results in a table. The example on Stackblitz is similar to what I am trying to achi ...

Is there a way to add an event listener to dynamically generated HTML using the v-html directive?

I have a string variable named log.htmlContent that contains some HTML content. This variable is passed into a div to be displayed using v-html. The particular div will only be displayed if log.htmlContent includes an img tag (http: will only be present in ...

Transfer a file using fetch (POST request) within a TypeScript React component

i am trying to send a file to an api using fetch. this is the api: and here is how it wants to be handled: You can perform Ogre transformations directly by making a HTTP POST request: Convert to GeoJSON http://ogre.adc4gis.com/convert with the following ...

What is the process for attaching an analytics tag to data messages using the Firebase Admin SDK with Javascript or TypeScript?

Adding a label to my message is something I'm trying to do. I checked out the official guidelines here and found a similar question answered on Stack Overflow here. I've been attempting to implement this in JavaScript, but I'm stuck. Here& ...

Tips for transferring several parameters from an Angular 8 application to a .NET Core API

Hello, I am facing an issue with passing multiple string parameters from an Angular 8 app to a .NET Core API. This is my first time posting a question so I will try to provide all the necessary details. Here is the Angular code snippet: import { Injectab ...

Transform an angular1 javascript circular queue implementation for calculating rolling averages into typescript

I am currently in the process of migrating a project from Angular 1 to Angular 2. One of the key components is a chart that displays a moving average line, which requires the use of a circular queue with prototype methods like add, remove, and getAverage. ...

Steps to activate a function within an angular6 form-related directive

Is there a way to execute a function within a directive when the form is marked as pristine? I want to apply a CSS class to a tab header when the form is pristine. <form [formGroup]="awayForm" (ngSubmit)="onSubmit()" awayConfirm [cancelClicked]="cancel ...

Encountered a TypeScript error: Attempted to access property 'REPOSITORY' of an undefined variable

As I delve into TypeScript, a realm unfamiliar yet not entirely foreign due to my background in OO Design, confusion descends upon me like a veil. Within the confines of file application.ts, a code structure unfolds: class APPLICATION { constructor( ...

How to prevent users from accessing the app through standard web browsers in an Express/Electron application

My setup involves an express server that serves my angular front end at http://localhost:9000 Utilizing electron as a desktop client is part of my project. I am aiming to restrict users from accessing the application through any browser except electron. ...

Angular 7 error: No provider found for PagerService causing NullInjectorError

I have been struggling to get pagination working properly in my project. Below is the code I have written: pager.service.ts: import * as _ from 'underscore'; @Injectable({ providedIn: 'root', }) export class PagerService { ...

JSX tags without any inner content should be self-closed

After successfully running this code, I encountered an issue when committing it to git. The error message 'ERROR: src/layouts/index.tsx:25:9 - JSX elements with no children must be self-closing' appeared. I attempted to resolve the error by addi ...

Troubleshooting the issue of the Delete Service not functioning properly within Angular

ListStore.ts file export class ListstoreComponent implements OnInit { rawlist; name = ''; id = ''; storeid = ""; store: Store; constructor(private api: APIService, private router: Router, private route: ActivatedRoute, pri ...