angular AppComponent 在子组件之后加载

angular AppComponent loads after sub component

我在 AppComponent 中加载数据

然后在people.component

中引用这个数据

但 people.component 首先加载。

应用组件

  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 数组的第一个元素之前显示 "people.component getPeople()"。

所以,我无法利用人员组件中的人员数组。

关于如何让 AppComponent 在 people.component 之前达到 运行 的任何想法?

假设 PeopleComponent 是 AppComponent 的子组件,并且它有一个关联的模板,可以使用异步管道将数据传递到输入 属性。

app.component.ts

people$: Array<People>;

ngOnInit(): {
    this.people$ = this.getDATA(this.URL);
}

app.component.html

<app-people *ngIf="people$ | async as people" [people]="people"></app-people>

people.component.ts

@Input() people: Array<People>;

[...remaining code elided...]

我认为您拥有的 appData 是您在 PeopleComponent 中注入的依赖项,用于获取 AppComponent 从某些 REST API 获取的数据].这是您创建的共享服务,用于在 AppComponentPeopleComponent 之间传递数据。但是他们有 Parent-Child 关系,你可以简单地使用 @Input 属性 在他们之间传递数据。所以我不确定你为什么要使用共享服务来做到这一点。

从您的 OP 假设,PeopleComponentAppComponent 的 child,因此您可以简单地将 people 作为 @Input() [=38] =] 到 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.