IONIC – ANGULAR Why when click back button I have same multiple request?

Issue

I have the back button on my pages.
When I stay on PAGE 1 and go to PAGE 2 I have only one request. And when I click the back button from PAGE 2 to PAGE 1 i receive a two same request. If I go to PAGE 2 again and go back I receive three same request.

Why ?

i have this on PAGE 1

ionViewWillEnter() {

    this.route.paramMap.subscribe(paramMap => {
      if (!paramMap.has('id_store')) {
        this.location.back();
        return;
      }
    this.isLoading = true;

    this.atv_id = paramMap.get('id_store');


        this.loadingCtrl
        .create({ keyboardClose: true, message: 'Carico categorie...' })
        .then(loadingEl => {
          loadingEl.present();

          this.subcriber = this.ristoserv.postRistoCategories(this.atv_id).subscribe( (response: any ) => {

            // check zona selezionata
            this.storage.getObject('zoneData').then((data: any) => {
            });

            this.categories = response;
            this.IdType = paramMap.get('id_type');

            this.isLoading = false;
            loadingEl.dismiss();

          }, errRes => {

            loadingEl.dismiss();
            const code = errRes.error.error.message;
            console.log('error', code);
            this.isLoading = true;

          });
        });
    });
  };

Solution

Every time you call ionViewWillEnter() you create new route subscription.
You should unsubscribe from it.

Create property

private unsubscribe$ = new Subject<void>();

use it to unsubscribe

this.route.paramMap
  .pipe(takeUntil(this.unsubscribe$))
  .subscribe(paramMap => {

And emit it whenever component destroys.

ngOnDestroy() {
  this.unsubscribe$.next();
}

You can do this easier using a library @ngneat/until-destroy.

Or simply make sure you only initialize it once: if you only change parameter in your router it might not recreate your component – depending on onSameUrlNavigation config.

It would help if you showed how/when you call ionViewWillEnter().

Answered By – Bojan Kogoj

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published