Stop receiving updates from an observable once you navigate away from an Onsen UI page

I am facing an issue with my Angular 2+ app that utilizes Onsen UI. I have set up some components as pages and I am using the ons-navigator to switch between them.

The problem arises when I subscribe to an observable in an ons-page and the user navigates away from that page. The observable remains active even though it seems like ngOnDestroy is not being called when changing pages using the onsen navigator.

I am searching for a solution to this problem. Any ideas?

Here's a snippet of the 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 {
    //not working
    console.log('on destroy called.');
  }

}

Answer №1

This particular behavior is often seen in OnsNavigator. To stop receiving notifications from the observable once the page has been pushed, you can include the unsubscribe action after the promise pushPage. Building on Thakur's solution, your code would resemble something 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());
    });
  }

}

Answer №2

If the component is not going to be destroyed, you might need to explore a different approach such as subscribing to router changes and unsubscribing from your subscribers.
Check out this reference link for more information.

constructor(private router: Router) {
    router.changes.subscribe((val) => {
     /*You can console log the value here to see if there is anything useful that would help in adding logic to unsubscribe from your observers instead of relying on the ngOnDestroy hook.*/
    })
  }

I hope this solution proves helpful. Happy Coding!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Angular 2+, what is the best method for displaying elements based on whether the user is logged in or logged out?

Struggling with the transition from AngularJS to Angular 2+ for my app. I'm facing challenges implementing a simple feature that was previously effortless in AngularJS. The issue is with the top navigation - I want it to display a LOG IN button when ...

Unexpectedly, a significant ngrx createEffect leads to an unusual error following an update, but the issue vanishes when certain code snippets like tap or filter are disabled

I have been in the process of upgrading a massive Angular 12 project to Angular 13 and have completed several steps. One significant change was the rewriting of Effects using a newer approach like createEffect(() => instead of @Effect However, during ...

Understanding the significance of the term "this" in Typescript when employed as a function parameter

I came across a piece of TypeScript code where the keyword "this" is used as a parameter of a function. I'm curious to know the significance of this usage and why it is implemented like this in the following context: "brushended(this: SVGGElement) {". ...

Hovering over the Chart.js tooltip does not display the labels as expected

How can I show the numberValue value as a label on hover over the bar chart? Despite trying various methods, nothing seems to appear when hovering over the bars. Below is the code snippet: getBarChart() { this.http.get(API).subscribe({ next: (d ...

What is the reason that {a: never} is not the same as never?

Is there a reason the code {a: never} cannot be simplified to just never? I believe this change would resolve the issues mentioned below. type A = {tag: 'A', value: number} type B = {tag: 'B', value: boolean} type N = {tag: never, valu ...

Issue in kendo-angular-upload: Failure to trigger error event following a 500 Server Error Code

When developing the Front End, I utilize Angular 7 to attempt uploading an image using Kendo: <kendo-upload [saveUrl]="uploadSaveUrl" [removeUrl]="uploadRemoveUrl" [restrictions]="uploadRestrictions" [mul ...

The array remains undefined even after being assigned within the subscribe function

I have encountered an issue in my Angular app where the array productLocations is being assigned in the ngOnInit method within a subscription, but it remains undefined when used in another method. Despite following advice on Stackoverflow to move the assig ...

Initiate the deployment of the updated npm package

After I installed the npm package ngx-cookie-service, I made changes to the code in the node_module > ngx-cookie-service folder. While these changes worked perfectly on my local host, they did not work when I deployed my Angular app to Azure. What step ...

What is the best way to patiently anticipate a response from customer service

My singltone service contains a synchronous method. Upon injecting the service into a component: constructor( private reonMapLibraryService: ReonMapLibraryService ) {} I am unable to access reonMapLibraryService.data; immediately because it is an asy ...

How can I retrieve all values in an object in Angularfire2 without needing to reference the key of the parent object?

I am looking to retrieve every object listed under each date within a specific expense category from the Firebase Database. Under the Firebase structure: - expenses - food - 07-11-2016 //"I want every object in here" + -KX7A ...

Angular throws a NullInjectorError when a unit test fails due to issues with dependency

As a newcomer to Angular, I am struggling to grasp the concept of Dependency Injection (DI) and how it functions. My current challenge involves trying to pass a unit test successfully. Below is the code for the test; import { TestBed } from '@angula ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

I'm having trouble getting the new Angular @if template syntax to function properly in my web application

Can anyone provide assistance? I'm encountering an issue with the new Angular @if template syntax in my angular webapp. It appears that the syntax is not being recognized as valid. Here's an example: https://i.sstatic.net/2PKXHoM6.png If anyon ...

Spring Boot - The Ultimate Guide to Hosting Angular2 Compiled Files

Currently, I am using a Spring Boot restful server alongside an Angular2 front-end application. In an attempt to streamline the process, I have been trying to host the front-end files on Tomcat in order to avoid serving them separately. Unfortunately, desp ...

Looking for a specific phrase in the data entered by the user

I am dealing with data in ckeditor that looks like this: <p>test 1</p> <p>test 2</p> <p><img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICw ...

There is no assigned value in scope for the shorthand property. You must either declare one or provide an initializer

I'm just starting out with TypeScript. Encountering the error 'No value exists in scope for the shorthand property 'firstName'. Either declare one or provide an initializer.' while using Prisma with Next.js to create a new user in ...

Steps for adding an input box to an md-menu item

I'm looking for an option that allows me to either add an item to an existing list or create a new one, similar to YouTube's 'Add to playlist' feature. The current implementation sort of works, but the menu disappears as soon as the inp ...

Having difficulty initializing a constant object in TypeScript

Encountering an error while attempting to compile my code using Angular 7.2.0 and TypeScript version 3.2.2: Error TS1005: ',' expected.**… The issue seems to be arising from the line where I am trying to define a const object. addAppareil( ...

Exploring ways to capture all console outputs or retrieve the current console content in frontend development

Currently working with Angular and looking to integrate a bug reporting feature into my application. I want to capture the content of the browser's console for debugging purposes. However, I'm unsure of how to access it. Not all errors are logge ...

Creating a custom Angular filter to group every 3 items within an iteration into a new div container

When attempting to organize three instances of app-story-preview within a wrapper div using a ngFor loop, I encountered the following code: <ng-template [ngIf]="stories.length > 0" [ngIfElse]="empty"> <cdk-virtual-scroll-viewport [itemSize ...