Is the communication between Angular service and component failing when using ngFor?

I am currently using Angular to create a video game page. When a specific title is clicked, the id is sent to make an API call with that specific id. I am able to retrieve the data in the selected-games component where I intend to use it, but when I use ngFor, nothing is shown – no errors and no data.

The home component is where you can select a specific video game. I tried adding setTimeout and routing to this TypeScript file, hoping to delay the routing until the array in the selected-game-component is loaded, but it did not work.

constructor(private getGame: SelectedGameComponent, private router: Router) { }

  ngOnInit(): void {
    
  }

  sendId(id: any){
     // this.gamesService.functionGetGameById(id);
     this.getGame.test(id);

     setTimeout(() => {
       this.router.navigateByUrl('game');
     }, 5000);
  }
}

In the selected game component, I am attempting to map the data in the HTML file.

game: any = [];
constructor(private getGames: FetchingVideoGamesService) { }

test(id: any){
    this.getGames.functionGetGameById(id).subscribe(response =>{
      this.game = response;
      console.log(this.game);
    });
  }
}

And now, the fetching service:

 functionGetGameById(id: any){
    return this.http.get<any>('https://api.rawg.io/api/games/'+id+'?key=keyremovedforpost')
      .pipe(map(response =>{
        const gameArray: any = [];
        gameArray.push(response);
        console.log(gameArray, 'response from service');
        return gameArray[0];
      }));
  }

Answer №1

Instead of directly injecting a child component into the parent component, consider using a service for better organization and separation of concerns.

A recommended approach is to have the parent component call functionGetGameById() from the service in a reactive manner. Once the data is retrieved by the parent, it can then pass it down to the child component.

Parent Component

export class ParentComponent {
  games$!: Observable<any[]>;

  constructor(private getGames: FetchingVideoGamesService) { }
  
  callTheService(id: string): void {
    this.games$ = this.getGames.functionGetGameById(id);
  }
}

Parent HTML

...
<your-child-component [theGames]="games$ | async">
</your-child-component>

Child Component

...
export class ChildComponent {
  @Input() theGames!: any[];
}

Child HTML

<div *ngFor="let game of theGames">
 {{ game }}
</div>

This approach ensures one-way communication between components with the parent handling business logic as a smart component and the child focusing on specific tasks as a dumb component. If the child needs to send data back to the parent, utilize an Output event emitter.

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

JavaScript now has Type Inference assistance

When attempting to utilize the Compiler API for processing JavaScript code and implementing Type inference to predict types of 'object' in a 'object.property' PropertyAccessExpression node, I encountered some issues. Some simple example ...

A guide to utilizing ngFor in Angular 7 to loop through nested JSON and display it in a ul li

Looking to insert a nested JSON into an unordered list using ngFor loop in Angular. Here's the expected output format in HTML: home.component.html <div class="col-md-3" id="leftNavBar"> <ul *ngFor="let item of nestedjson"> <li c ...

Using Angular to enhance a Bootstrap NavBar with a Dropdown feature

I've been attempting to implement the default NavBar from Bootstrap documentation directly as shown in the examples. However, it seems to be not functioning properly. The UI displays correctly but the dropdown feature is not working. Please refer to ...

Creating a structured state declaration in NGXS for optimal organization

Currently, I'm delving into the world of NGXS alongside the Emitters plugin within Angular, and I find myself struggling to grasp how to organize my state files effectively. So far, I've managed to define a basic .state file in the following man ...

Cannot execute npm packages installed globally on Windows 10 machine

After installing typescript and nodemon on my Windows 10 machine using the typical npm install -g [package-name] command, I encountered a problem. When attempting to run them through the terminal, an application selector window would open prompting me to c ...

Retrieve content from my Tumblr API posts

Looking to retrieve my tumblr posts through an api. Successfully set up the api key using Angular2 and typescript. Utilizing jsonp to avoid any cross origin problems. Here is my current code snippet: var config = { params: { action: "query" ...

Can the Angular Material Mat Stepper display multiple active/in-progress steps simultaneously?

Has anyone figured out how to display multiple steps simultaneously on Angular Mat Stepper? I've only been able to show one step at a time and haven't found a solution yet. Any insights would be greatly appreciated. https://i.stack.imgur.com/VK ...

Setting up a Variable with an Object Attribute in Angular

I am attempting to create a variable that will set a specific property of an object retrieved through the get method. While using console.log in the subscribe function, I am able to retrieve the entire array value. However, as a beginner, I am struggling ...

Web performance issues noticed with Angular 8 and Webpack 3.7 rendering speed

My web application is currently taking 35 seconds to render or at least 1.15 seconds from the initial Webpack start. I've made efforts to optimize Webpack, which has improved the launch speed, but the majority of time is consumed after loading main.j ...

Leverage the spread operator (or an equivalent method) to transfer all attributes from a solitary mixin

When working with the example below, my goal is to pass only the properties of MyMixedInProps to MyChildComponent using a method similar to the spread operator ({...props}). In my specific scenario, MyMixedInProps is defined in a third-party library (whic ...

Having trouble installing @angular/cli 4 on Debian?

I'm having trouble installing @angular/cli on my Debian box. I already have the latest versions of Node.js and npm installed. Interestingly, Angular4 works perfectly fine on my Windows machine where I use it daily. However, when I try to get it runnin ...

Is there any distinction between using glob wildcards in the tsconfig.json file when specifying "include" as "src" versus "include" as "src/**/*"?

Is there a distinction between these two entries in the tsconfig.json file? "include": ["src"] "include": ["src/**/*"] Most examples I've come across use the second version, but upon reviewing my repository, ...

The name 'Diagnostics' cannot be located

I've downloaded the Typescript repository and am currently reviewing the code. However, I keep encountering this recurring error message: Cannot find name 'Diagnostics' This error pops up on lines that are similar to this: Diagnostics._ ...

Angular 10 - Compilation errors caused by the element's location

When running 'ng serve' or 'ng build' in Angular 10, I encountered a build error that stated: ERROR in projects/project-navigator/src/app/modals/building-permissions.component.html:89:61 - error NG8002: Can't bind to 'ngClass& ...

Exploring Angular unit testing for immutable variables

Currently, I am working on writing unit tests for a specific class that contains readonly class variables. I am trying to ensure complete test coverage and understand how to cover the logic inside these variables. import { Injectable } from '@angu ...

What are some best practices for managing object-level variables in TypeScript and Vue.js?

Uncertain about the optimal approach, I am looking to create a component and leverage some object level variables. Consider the example below: import Vue from "vue" import * as paper from "paper" export default Vue.extend({ template: ` <d ...

Angular 13 throws NG0301 error message, failing to display the problematic module

Can someone provide assistance? Recently, I upgraded my Angular project from version 11 to version 13: Angular: 13.2.4 ... animations, cdk, common, compiler, compiler-cli, core, forms ... platform-browser, platform-browser-dynamic, router Package ...

A guide on resolving the issue with node module live-server by switching from using require('opn') to require('open')

While attempting to deploy to my AWS environment, I encountered an error in the nodejs.log. /var/app/current/node_modules/opn/index.js:11 const wslToWindowsPath = async path => { ^^^^ SyntaxError: Unexpected identifier ...

Tips for showing that every field in a typed form group must be filled out

Starting from Angular 14, reactive forms are now strictly typed by default (Typed Forms). This new feature is quite convenient. I recently created a basic login form as shown below. form = this.fb.group({ username: ['', [Validators.required ...

Issue encountered with Typescript and Mongoose while operating within a Kubernetes cluster environment with Skaffold configuration

Here is the code snippet, const userSchema = new mongoose.Schema({ email: { type: String, required: true, }, password: { type: String, required: true, }, }); console.log(userSchema); userSchema.statics.build = (user: UserAttrs) =& ...