gpt4 book ai didi

Angular AppComponent 在子组件之后加载

转载 作者:行者123 更新时间:2023-12-03 06:04:56 25 4
gpt4 key购买 nike

我在AppComponent中加载数据

然后在people.component中引用这些数据

但是 people.component 首先加载。

应用组件

  ngOnInit() {
pre: this.getPeople();
}

getPeople(): any {
this.getDATA(this.URL)
.subscribe(people => {
this.people = people,
console.log(people[0]);
});
}

人员组件

ngOnInit() {
pre: this.people = this.appData.people;
this.getPeople();
}

getPeople(): any {
console.log("people.component getPeople()");
}

控制台在显示 people 数组的第一个元素之前显示“people.component getPeople()”。

因此,我无法利用人员组件中的人员数组。

关于如何让 AppComponent 在 people.component 之前运行有什么想法吗?

最佳答案

我认为您拥有的 appData 是您在 PeopleComponent 中注入(inject)的依赖项,以获取 AppComponent 正在获取的数据来自一些 REST API。它是您创建的共享服务,用于在 AppComponentPeopleComponent 之间传递数据。但它们具有父子关系,您可以使用 @Input 属性在它们之间简单地传递数据。所以我不确定您为什么要使用共享服务来做到这一点。

假设您的OP中,PeopleComponentAppComponent的子级,因此您可以简单地将people作为@Input传递() 属性到 PeopleComponent

只需将其添加到 app.component.html 中即可:

...
<app-people [people]="people"></app-people>
...

现在在 PeopleComponent 中定义一个 @Input 属性。像这样的事情:

import { Component, OnInit, Input } from '@angular/core';

@Component({
selector: 'app-people',
templateUrl: './people.component.html',
styleUrls: ['./people.component.css']
})
export class PeopleComponent implements OnInit {

@Input() people: any;

ngOnInit() {
pre: this.people = this.people;
this.getPeople();
}

getPeople(): any {
console.log("people.component getPeople()");
}

}
<小时/>

Here's a Working Sample StackBlitz for your ref.

关于 Angular AppComponent 在子组件之后加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53948839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com