Zichen Ma
Zichen Ma

Reputation: 987

angular (version 8) pass async @input value to fetch another call

I have a parent component that has a button when the user clicks it will make a request and passed the data into a child component (a ngx-bootstrap modal). The child component will use the async data to make another request to render its UI.

My parent component is like this:

<Parent>
<child-modal [subSectionInfo]="subSectionInfo"></child-modal>
</Parent>

the subSectionInfo is async data retrieved from an ajax in Parent component.

My child component will make call like this:

  ngOnInit() {
   const id = this.subSectionInfo.id;
   this._fetchData(id)
  }

   private _fetchData(id: number) {
     this.service
     .getData(id).pipe(
     .subscribe((data: any) => {
      this.list = data;
   });
  }

However, this always gives me undefined which causes the child component ajax call failed. Is any way to solve this issue? Thank you so much in advance!

Upvotes: 0

Views: 263

Answers (1)

Currently, your code does not wait on the first request to complete. While the request for subSectionInfo is being made in the parent component, it's value is undefined since the value hasn't returned from the server yet. This is why the child component get's undefined. There are 2 ways to approach this.

  1. In your parent component, you can wait until the data is loaded and then pass in subSectionInfo to your child component.
  2. In your child component, you can make use of the ngOnChanges life-cycle hook. This is where your child component implements OnChanges. You can read more about it here.
 ngOnChanges(changes: SimpleChanges) {
   if (changes['subSectionInfo'].currentValue !== undefined) {
      const id = this.subSectionInfo.id;
      this._fetchData(id)
   }

 }

  private _fetchData(id: number) {
    this.service
      .getData(id).pipe(
      .subscribe((data: any) => {
        this.list = data;
    });
  }

Hope this helps

Upvotes: 1

Related Questions