简体   繁体   中英

await fetch Angular between components via Input

I'm making a request with fetch to the reqres api users in app.component, then i share data to his child component (hello.component) via Input. I get the correct user names in child template, I'm trying to print the users in console but i get an empty array. It's there a way to 'await' the response of another component? i guess this is an asynchronous issue. Here is the link: https://stackblitz.com/edit/angular-ivy-b3m1kp?file=src%2Fapp%2Fhello.component.ts

Thanks in advance.

app.component:

 import { Component, VERSION, OnInit } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { public usuarios; constructor(){ this.usuarios = []; } ngOnInit(){ this.getUsers(); } getUsers(){ fetch('https://reqres.in/api/users') .then(data => data.json()) .then(users => { this.usuarios = users.data; console.log(this.usuarios); }); } }

hello.component:

 import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'hello', template: `<h1 *ngFor="let user of usuarios">Hello {{user.first_name}} </h1>`, styles: [`h1 { font-family: Lato; }`] }) export class HelloComponent{ @Input() usuarios; ngOnInit(){ console.log(this.usuarios); } }

app.component.html:

 <hello [usuarios]="usuarios"></hello>

As the fetch operation is asynchronous, usuarios array would be empty upon initialization for the child. To detect the value changes move logic which will use the fetched results to ngOnChanges. Like this:

 ngOnChanges(changes: SimpleChanges) {
    const { previousValue, currentValue } = changes.usuarios;
    if (previousValue !== currentValue) {
      console.log(this.usuarios);
    }
  }

Having a condition to check if the value has changed inside ngOnChanges is essential, otherwise the logic will be constantly triggered.

<hello *ngIf="usuarios.length>0" [usuarios]="usuarios"></hello>
<p>
  Start editing to see some magic happen :)
</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM