[英]await fetch Angular between components via Input
我正在向 app.component 中的 reqres api 用户发出 fetch 请求,然后我通过 Input 将数据共享给他的子组件(hello.component)。 我在子模板中得到了正确的用户名,我试图在控制台中打印用户,但我得到一个空数组。 有没有办法“等待”另一个组件的响应? 我想这是一个异步问题。 这是链接: https : //stackblitz.com/edit/angular-ivy-b3m1kp?file=src%2Fapp%2Fhello.component.ts
提前致谢。
应用程序组件:
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); }); } }
你好。组件:
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>
由于 fetch 操作是异步的,usuarios 数组在为孩子初始化时将为空。 要检测值更改移动逻辑,它将使用获取的结果到 ngOnChanges。 像这样:
ngOnChanges(changes: SimpleChanges) {
const { previousValue, currentValue } = changes.usuarios;
if (previousValue !== currentValue) {
console.log(this.usuarios);
}
}
有一个条件来检查 ngOnChanges 中的值是否已更改是必不可少的,否则逻辑将不断触发。
<hello *ngIf="usuarios.length>0" [usuarios]="usuarios"></hello>
<p>
Start editing to see some magic happen :)
</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.