DevQuayle
DevQuayle

Reputation: 358

ionic angular4 action after load data from few requests

I have problem with hiding load after load data from two requests. I want show loader before start loading data and hiding loader after all requests done. I don't have idea how resolve it.

 export class HomePage {
    Products: Product[];
    Baners: Baner[];

    constructor(private navCtrl: NavController,
                private productsService: ProductsService,
                private BannerService: BanersService) {
    }

    /**
     * Get products
     */
    loadProducts(): void {
        this.productsService.getOnHomepage().subscribe((products) => {
            this.Products = products;
        });
    }

    /**
      * get baners    
    */
    loadBaners(): void {
        this.BannerService.getOnHomepage().subscribe((baners) => {
            this.Baners = baners;
        });
    }


    loadData(): void {
        // I want to show the loader

        this.loadProducts();
        this.loadBaners();

        //I want to hide the loader

    }



 ionViewWillEnter(){
        this.loadData();
    }

     }

Upvotes: 1

Views: 40

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

You are depending on two observables emitting once. The best way to do this depends on your use case (can you load either multiple times for example) but I think combineLatest will work best for you here. I would also suggest using the async pipe in your template rather than manually subscribing.

export class HomePage {
    Products = this.productsService.getOnHomepage();
    Banners = this.BannerService.getOnHomepage();

    constructor(private navCtrl: NavController,
            private productsService: ProductsService,
            private BannerService: BannerService) {
    }

    ionViewDidLoad() {
      /* show loader here */
      combineLatest(this.Products, this.Banners).take(1).subscribe(/* hide loader here */);
    }
}

Here I load the data and display a loading indicator when the page loads. When both Products and Banners have been loaded (emit once) you can hide the loader.

Upvotes: 1

Related Questions