Display Loading Component while using Observable with Async pipe


#1

Anyone has a “recipe” of how to use the Ionic 2 Loading component while using async pipe to resolve observables?

I have a page that make usage of a custom component:

<ion-content>
  <component [products]="productService.products$ | async"></component>
</ion-content>

How to display the Ionic 2 Loading component while productService.products$ is not resolved?

Thanks for help!


#2

I think that’s probably outside the scope of the AsyncPipe. You could have a backing boolean in the controller that determines whether the loading component is displayed, and update it on a subscription to the productService call, or store products in a component variable and use that variable being undefined or not as the trigger for the loading component. I only use the AsyncPipe for situations where it’s self-contained.


#3

I’m using a lot of Async Pipes, I’m not sure if the best solution, but it’s easier to handle because you don’t need to unsubscribe.

What do you mean with “self-contained”?

My project uses angularfire2 and has some data services that returns FirebaserListObservable that will be pass to child components using the async pipe.

That way I don’t have almost any .subscribe in my project. But now I ended up in this case of make usage of loading component.


#4

“Not needing to interact with any part of the app outside of the component using the AsyncPipe”. I understand and appreciate why you’re trying to do what you do, but if I were the author of AsyncPipe, I couldn’t think of an easy way to expose what you are asking for.


#5

Hi @paulogr,

This might be what you’re looking for. If I understand you correctly, you want to show a “Loading” indicator while the data is being streamed and dismiss the loading when it completes. Here’s my implementation.

ngOnInit() {
    this.products = this.productService.products$.do(
      collection => { this.hideSpinner() },
      error => {
        this.hideSpinner()
      }
    )
    this.showSpinner()
}

Let me know if you’re figured out a better way. Cheers.


#6

Super! This approach worked for me exactly as I wanted!