angular AppComponent loads after sub component

Viewed 981

I load data in AppComponent

and then refer to this data in people.component

But people.component loads first.

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()");
 }

The console display "people.component getPeople()" before it displays the first element of the people array.

So, I can't leverage the people array in the people component.

Any ideas on how to get the AppComponent to run before the people.component?

2 Answers

Assuming that the PeopleComponent is the child of the AppComponent, and that it has an associated template, one could use the async pipe to pass data into an input property.

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...]

I think the appData that you have is a dependency that you've injected in your PeopleComponent to get the data that AppComponent is getting from some REST API. It's a shared service that you've created to pass data between AppComponent and PeopleComponent. But they're having a Parent-Child relationship, you can simply pass data between them using an @Input property. So I'm not sure why you're doing that using a Shared Service.

Assuming from your OP, PeopleComponent is a child to the AppComponent, so you can simply pass people as an @Input() property to the PeopleComponent.

Just add this in the app.component.html:

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

And now define an @Input property in your PeopleComponent. Something like this:

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.

Related