How to Prevent Child Component Destruction When Re-fetching Data with Angular Observables

Discussão em 'Angular' iniciado por Mo3bius, Novembro 18, 2024.

  1. Mo3bius

    Mo3bius Guest

    I have an Angular app that makes multiple HTTP API calls. I combine the results of these APIs into a single stream of data, which is then passed as inputs to child components. In the template, I use the async pipe to subscribe to the stream and only display the child components when the data is available.

    Here’s the code I’m working with:

    Component Code:


    ngOnInit(): void {
    this.getData();
    }

    getData() {
    const apiDataOne$ = this.http.get<One[]>(URLOne);
    const apiDataTwo$ = this.http.get<Two[]>(URLTwo);

    this.dataStream$ = forkJoin([apiDataOne$, apiDataTwo$]).pipe(
    map(([result1, result2]) => ({ result1, result2 }))
    );
    }

    updateData() {
    this.getData();
    }

    HTML Template:


    @if(dataStream$ | async as dataStream){
    <child-component [input1]="dataStream.result1" [input2]="dataStream.result2">
    </child-component>
    }

    Issue:


    I want to trigger the getData() method dynamically, such as when a user clicks a button. However, when I call getData() again, it resets the dataStream$ observable. This causes the async pipe to emit null or undefined for a short time, which results in the child component being destroyed and recreated.

    I want to prevent the child component from being destroyed and recreated, even when the data is re-fetched.

    Questions:

    • How can I prevent the child component from being destroyed and recreated when the data stream is updated?
    • Is there a way to update the observable without causing the child components to be destroyed?

    Continue reading...

Compartilhe esta Página