Unable to transfer data from service to component

Just started mastering Angular.
I've successfully set up an API with Spring-boot and developed some Angular components to display the data, but unfortunately, nothing is showing up.

In my Angular project, I've created a Service to handle all the API requests.
Within this service, I initialized an empty array of type 'any' like this:

  locations : any[] = [];

Then, I made a GET request and assigned the response value to the array inside a method:

getAllLocations(){
    this.http.get("http://localhost:9595/oota-reg/api/locations/all").subscribe({
      next : (response : any) =>{

        console.log(response);
        
        this.locations = response;
 
      },
      error : (error) => {
        console.log("Oops! Something went wrong..", error);
        
      }
    })
  }

Now, moving on to creating two more components, namely the Home component and a Card component, just basic stuff.

The responsibility of the home component is to loop through all elements in the array and display a card for each element using the Card component.

    <div class="flex justify-center flex-wrap gap-5">
        @for (item of cards; track $index) {
            <app-card></app-card>
        }@empty {
            <p>none</p>
        }
    
    </div>

However, the issue arises in the home.component.ts file where I intended to create an array named 'cards',
inject the Service, and assign the array value from the Service after the GET call.

 private locationService : LocationService = inject(LocationService);

  public cards : any[] = [];

  ngOnInit(): void {

    this.locationService.getAllLocations();

    this.cards = this.locationService.locations

    console.log(this.cards);
        
  }

But unfortunately, the 'cards' array remains empty.
How can I properly pass the data?

Answer №1

The code contained within the subscribe function is asynchronous, meaning it waits for the API to complete. On the other hand, the code outside of the subscribe function is synchronous, meaning it does not wait. This creates a problem because we are trying to access a property before the API call has finished. The solution is to move the assignment code inside the subscribe function so that it executes only after the API call is completed.

getAllPlaces(){
  return this.http.get("http://localhost:9595/oota-reg/api/places/all")
}

Now the service returns an observable which can be subscribed to inside the component. It is recommended to subscribe to observables inside the component rather than in services.

  ngOnInit(): void {
    this.placeService.getAllPlaces().subscribe({
      next : (response : any) =>{
        console.log(response);
        this.placeService.places = response; // can be removed if not needed!
        this.cards= response;
        console.log(this.cards);
      },
      error : (error) => {
        console.log("Something went wrong..", error);
      }
    })
  }

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

Encountered an Ionic error: TypeError stating that the function _co.toggleRecoder is not recognized

Currently, I am immersed in an Ionic project where a perplexing error has reared its head. The error message reads: ERROR TypeError: _co.toggleRecoder is not a function Featured below is the TypeScript code snippet, showcasing the implementation of th ...

"The OnPush change detection mechanism fails to detect changes when a new reference is passed as input to a child

Within my Angular application, I have set up 2 nested components: a parent component called AppComponent and a child component named TooltipComponent. Both components are utilizing the OnPush change detection strategy. My objective is to update the child c ...

What is the best way to obtain an error as an object when subscribing to an HTTP GET request

I am working on an asp.net core webApi along with an Angular9 WebApp. My goal is to retrieve the error in a subscribe as an object rather than just a string. this.http.post<TestSystem>(this.url, testsystem).subscribe((result) => { // do someth ...

Angular Typescript error: Trying to assign a value to 'someProperty' property of an undefined object

Within my Article class, I have a property called Image which is structured like this: export class Article { public image:Image; public images: Image[]; } If I decide to comment out this.article.image = new Image(); in the following way: constru ...

Guide on looping through an array of objects and eliminating each item using JavaScript

someArray = [{name:"Ibrahim", cid:322}, {name:"Ismail", cid:423}]; Exploring this task further, I am seeking a reliable method to iterate over the array, perform certain actions, and eventually produce the desired output like so: someArray = []; This is ...

Transforming a table column into an array using VBA leads to an array with varying data types

I have a challenge where I need to convert a column from a table into an array and a range into a second array. After manually copy/pasting the same data with custom mmm-yy format, I noticed that once converted into arrays, they are of different types. Di ...

Module is absent in JavaScript but present in TypeScript

As I delve into coding a vscode extension by following a tutorial, I encountered an issue with importing in my server.ts file. The directory structure looks like this: ...

What is the best way to convert an enum into an array containing all the values of its items in TypeScript?

For example, consider the following TypeScript enum: export enum UserType { Guest = 1, SNS = 2, Account = 3, Certified = 4, } Is there a way to dynamically create an array with specific values without hard-coding them? const atrrib ...

How to Convert a Python List into JSON or CSV Format

Currently, I have a code snippet that converts my category tree into a list. What I'm trying to achieve next is to convert this list into CSV or JSON format. Each item in the list may contain multiple IDs, as illustrated below. def paths(tree): ...

Having trouble retrieving an object property in HTML or TypeScript within an Angular framework?

export class ComponentOne { array_all_items: Array<{ page_details: any }> = []; array_page_details: Array<{ identifier: number, title: string }> = []; initial_item: Array<{ identifier: number, title: string }> = [ { ...

Exploring Angular 4.3's HTTP Interceptor Retry功能

As I delve into my first attempt at coding, I find myself faced with the challenge of capturing 401 errors using HttpInterceptor. My goal is to generate a new auth token based on a certain condition and then retry the process with that token in place. Howe ...

Sign up for the identical Observable within a Child Component in Angular 2 using TypeScript

This question may seem simple, but as a newcomer to Angular 2, I often find myself needing more explanation despite the good examples and tutorials available. Within a component, I have an observable that gets updated periodically. While I've simplif ...

A guide to customizing cell text color in autoTable using jspdf with Angular2+ based on specific conditions

I am looking to change the text color to red and make it bold if the 'Target Data Type' and 'Data Type Verified' values in the title columns are different when using autoTable in jspdf. I have attempted to write a code for this in Angul ...

Accordion border in Bootstrap should be applied to all items except the first one

I am currently implementing Bootstrap accordions in an Angular application and I am facing an issue where I want to have a colored border all around each accordion panel. The problem is that by default, Bootstrap removes the top border from all accordions ...

Encountering a problem when attempting to utilize AngularFire's Cloud Messaging Angular module due to missing configuration values for the app

Working with Firebase Cloud Messaging in my Angular application using AngularFire2 has presented a challenge. I am facing an error when attempting to retrieve the user's current token. I have already set up the "firebase-messaging-sw.js" and "manifes ...

A guide to removing the path prefix from routes of components in lazy loaded modules

One interesting feature I have implemented is the lazy loading of a module called calendar.module, which is loaded in the app-routing.module like this: { path: "calendars", canActivate: [AuthGuard], loadChildren: () => import(". ...

Issues arise when trying to insert a control based on the index in an Angular Reactive FormArray

Below is the form structure I am working with: this.addForm = this.formBuilder.group({ details: this.formBuilder.array([]), }); To add a new control, I use the following function: nestedFormGroupDetails(control) { control.push( this.f ...

Calculating the combined total and mean values within an object using JavaScript

I have a set of data in the following format: { "Dates": ["January", "January", "March", "March", "March", "November", "November"], "Values": [45.6, 0.5, 59.3, 46.56, ...

Is it possible to declare the type of an object within a function call?

When working with TypeScript, it is possible to define a function and an interface like this: function someFunction(options: any) { // Do something } interface MyOptions { userId: number; verbose: boolean; } const options: MyOptions = { u ...

What is the best way to add a header field to a response using NestJS?

I am attempting to create a login function in my code, but encountering an issue: @Post('login') async login(@Body() body: AuthDto, @Res() res: Response) { const loginResponse = await this.authService.login(body); console ...