0

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!

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I took the first solution which works better than the second in my case!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.