我在AppComponent中加载数据
,然后在people.component中引用此数据
但是people.component首先加载。
AppComponent
ngOnInit() {
pre: this.getPeople();
}
getPeople(): any {
this.getDATA(this.URL)
.subscribe(people => {
this.people = people,
console.log(people[0]);
});
}
people.component
ngOnInit() {
pre: this.people = this.appData.people;
this.getPeople();
}
getPeople(): any {
console.log("people.component getPeople()");
}
控制台在显示人数组的第一个元素之前显示“ people.component getPeople()”。
因此,我无法利用人员组件中的人员数组。
关于如何使AppComponent在people.component之前运行的任何想法?
答案 0 :(得分:0)
假设PeopleComponent是AppComponent的子级,并且它具有关联的模板,则可以使用异步管道将数据传递到输入属性中。
people$: Array<People>;
ngOnInit(): {
this.people$ = this.getDATA(this.URL);
}
<app-people *ngIf="people$ | async as people" [people]="people"></app-people>
@Input() people: Array<People>;
[...remaining code elided...]
答案 1 :(得分:0)
我认为您拥有的appData
是一种依赖关系,您已将其注入PeopleComponent
中以获取AppComponent
从某种REST API获取的数据。这是您创建的共享服务,用于在AppComponent
和PeopleComponent
之间传递数据。但是他们之间存在亲子关系,您可以简单地使用@Input
属性在它们之间传递数据。因此,我不确定您为什么使用共享服务来做到这一点。
假设您的OP中PeopleComponent
是AppComponent
的子代,那么您可以简单地将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()");
}
}
这是您推荐的Working Sample StackBlitz。