Unsubscribe to observable when navigating away from an onsen ui page

982 Views Asked by At

I have an angular 2+ app running onsen ui, I have setup some components as pages and I am using the ons-navigator to switch between them.

The problem im having is that when im subscribed to an observable in an ons-page and the user navigates away from that page, The observable is still active. It seems like ngOndestroy doesnt get called when changing pages using the onsen navigator.

Im wondering how can I resolve this?

heres some code:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { OnsNavigator } from 'ngx-onsenui';
import { HomePageComponent } from '../home-page/home-page.component';
import { CommonDataService } from '../_services/common-data.service';
import { MenuService } from '../_services/menu.service';
import { UserService } from '../_services/user.service';

@Component({
  selector: 'ons-page',
  templateUrl: './login-page.component.html',
  styleUrls: ['./login-page.component.scss']
})
export class LoginPageComponent implements OnInit {

  constructor(
    private menuService: MenuService,
    private commonDataService: CommonDataService,
    private _navigator: OnsNavigator,
    private userService: UserService) { }
  

  ngOnInit() {
    this.menuService.changePage$.subscribe((page) => {
      this._navigator.element.pushPage(page, {data: {hoge: "fuga"}});
    });
  }

  ngOnDestroy(): void {
    //doesnt work
    console.log('on destroy called.');
  }

}
2

There are 2 best solutions below

0
Kevin Shiflett On

This seems to be normal behavior for OnsNavigator. If you want to unsubscribe from the observable after the page is pushed you can do this after the promise pushPage. Piggy-backing off of Thakur's answer it would look like this.

export class LoginPageComponent implements OnInit  {
  subscription: Subscription;

  constructor(
    private menuService: MenuService,
    private commonDataService: CommonDataService,
    private _navigator: OnsNavigator,
    private userService: UserService) { }
  

  ngOnInit() {
    this.subscription = this.menuService.changePage$;
    this.subscription.subscribe((page) => {
      this._navigator.element.pushPage(page, {data: {hoge: "fuga"}})
         .then(() => this.subscription.unsubscribe());
    });
  }

}
1
SaiSurya On

If the component will not be destroyed then you may have to consider a different approach like subscribing to router changes and unsubscribe to your subscribers.
Reference Link

constructor(private router: Router) {
    router.changes.subscribe((val) => {
     /*Here console log the value you find something useful to add some logic
      to unsubscribe to your observers instead of ngOndestroy hook.*/
    })
  }

Hope this helps, Happy Coding