"Unsubscribing in Angular via a button click: A step-by

I'm having trouble canceling a subscription for "device orientation" in Angular using (click) in HTML. I've tried multiple solutions but none seem to work. Does anyone have any ideas on how to fix this?

TS


// Watching the change in device compass heading
async watchOrientation() {

  var options = {
    frequency: 500,
  };

  this.orientation = this.deviceOrientation.watchHeading(options).subscribe( 
  (data: DeviceOrientationCompassHeading) => { this.orientation = data.magneticHeading.toFixed(2) },
(error: any) => console.log(error)
);
console.log('watchOrientation button clicked')
};

  // Stopping watching heading change
  async stopOrientation() {
    this.orientation.unsubscribe()
    console.log('stopOrientation button clicked');
};

HTML


<ion-item>
  <ion-icon name="pin" slot="start"></ion-icon>
  <ion-label>ion-item in a card, icon left, button right</ion-label>
  <ion-button fill="outline" slot="end" (click)="watchOrientation()" >Start</ion-button>
</ion-item>

<ion-item>
  <ion-icon name="pin" slot="start"></ion-icon>
  <ion-label>ion-item in a card, icon left, button right</ion-label>
  <ion-button color="danger" fill="outline" slot="end" (click)="stopOrientation()" >Stop</ion-button>
</ion-item>

Answer №1

Give this a shot:

Instead of simply storing the subscription, try to incorporate it in a way that prevents its loss during any subsequent assignments.

private subscription = new Subscription();

// Keep an eye on the device's compass heading changes
  async watchOrientation() {

    var options = {
      frequency : 500,
    };

    this.subscription.add(this.deviceOrientation.watchHeading(options).subscribe( 
      (data: DeviceOrientationCompassHeading) => { this.orientation = data.magneticHeading.toFixed(2) },
      (error: any) => console.log(error)
    ));
    console.log('WatchOrientation button has been clicked')
  };

    // Halt the observation of heading changes
    async stopOrientation() {
      this.subscription.unsubscribe();
      console.log('StopOrientation button has been clicked');
  };

Answer №2

Here is a solution that I found:

JavaScript

export class HomePage implements OnInit {

  subscription: Subscription = new Subscription();
  orientation: any;

  constructor(
    private route: ActivatedRoute,
    private deviceOrientation: DeviceOrientation
    ) { }

  ngOnInit() {
...
}

  }

  // Method to watch the device compass heading change
  watchOrientation() {

    var options = {
      frequency: 500,
    };

    this.subscription = this.deviceOrientation.watchHeading(options).subscribe( 
    (data: DeviceOrientationCompassHeading) => { this.orientation = data.magneticHeading.toFixed(2) },
    (error: any) => console.log(error)
    );
    console.log('button clicked')
    };
    
    // Method to stop watching the device compass heading change
    stopOrientation() {
      this.subscription.unsubscribe();
      console.log('stopOrientation()')
    };

}

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

Using ngFormModel with Ionic 2

How can I properly bind ngFormModal in my Ionic 2 project? I am facing an issue while trying to import it on my page, resulting in the following error message: Uncaught (in promise): Template parse errors: Can't bind to 'ngFormModel' since ...

Transforming Angular 2 quickstart application for deployment on Google Cloud infrastructure

Attempting to deploy a basic project on Google Cloud platform has proven to be more challenging than expected. The simple quickstart project can be accessed here, and functions flawlessly locally. While there are other providers like Heroku that offer one ...

Can TypeScript be implemented within nuxt serverMiddleware?

I recently began diving into the world of nuxtjs. When setting up, I opted to use typescript. Initially, everything was running smoothly until I decided to incorporate express in the serverMiddleware. Utilizing the require statement to import express funct ...

How can we regularly retrieve data in Angular 5 using Observables, while also incorporating instant fetching with RxJs 5.x?

Currently, I am in the process of developing a Single Page Application using Angular 5. One of the requirements is to periodically check if the API version matches the one loaded when the SPA was initialized. This check is essential to inform the user abou ...

Presenting data in various formats

I've got a JSON file with a list of data that includes months and years. I want to display all the months, but have the year only appear once in a big block area. Here's an image example: https://i.stack.imgur.com/Ps3OF.png The image demonstrates ...

The Sequence of Import Statements in Angular 2

The Angular Style Guide provides recommendations on Import line spacing: It is suggested to include one empty line between third-party imports and application imports. Consider arranging import lines in alphabetical order based on the module. For destruc ...

Issues with executing code within the react package for Yahoo Finance 2

I am currently in the process of developing a React application using Vite. The purpose of my app is to retrieve stock-related information from Yahoo using the yahoo-finance2 package. Interestingly, when I run the code as a standalone JavaScript file, eve ...

Angular4 does not recognize this.form.get as a valid function

While working on my Angular 4 application, I encountered an issue with data binding to a form. Despite the code for binding appearing correct, there seems to be a problem that I can't quite pinpoint. Upon debugging the application, I noticed that the ...

Troubleshooting deployment issues of an Angular 5 and ASP.NET Core 2.1 application on an nginx server

Trying to get my Angular 5 application deployed on Digital Ocean Ubuntu 16.4 Nginx, but running into some issues. I can successfully access the API endpoints: http:://ipaddress/api/values However, I am facing problems with the Angular website itself: T ...

AInspector WCAG evaluation found that mat-select does not meet level A compliance standards

As I work on making my website WCAG level A compliant, I've encountered an issue with the mat-select component in Angular material. After running checks with the AInspector extension for Firefox, it appears that the mat-select component lacks aria-con ...

Implementing an All-Routes-Except-One CanActivate guard in Angular2

In order to group routes within a module, I am aware that it can be done like this: canActivate: [AuthGuard], children: [ { path: '', children: [ { path: 'crises', component: ManageCrisesComponent }, ...

What does the (ERR! code ENOLOCAL npm ERR!) signify? Installation failed due to an error

When attempting to update the latest version of npm, I encountered the following error message: G:\>npm i -g npm ERR! code ENOLOCAL npm ERR! Could not install from "" as it does not contain a package.json file. npm ERR! A complete log of ...

Angular: Defining variables using let and var

When working with TypeScript and JavaScript, we typically use either let or var to declare a variable. However, in Angular components, we do not use them even though Angular itself uses TypeScript. For instance, export class ProductComponent implements OnI ...

Exploring the Power of TypeScript with NPM Packages: A Comprehensive Guide

I am working with a "compiler" package that generates typescript classes. However, when I attempted to run it using npm, an unexpected error occurred: SyntaxError: Unexpected token export To avoid the need for compiling local files, I do not want to con ...

What strategies can be utilized to manage a sizable data set?

I'm currently tasked with downloading a large dataset from my company's database and analyzing it in Excel. To streamline this process, I am looking to automate it using ExcelOnline. I found a helpful guide at this link provided by Microsoft Powe ...

Data binding with ngModel is contingent on certain conditions

I am facing an issue with conditional data binding using ngModel in Angular4. Let me explain further: I have a small form: <form-question-radio [(ngModel)]="model['q4']" name="question" [options]="[{value:true, label:'Yes'}, ...

How to store property transformation in Redux/ngrx

I have the following setup someReducer.ts export interface State { someProp: MyModel; } // some action listeners .. // // export const getProp = (state: State) => state.someProp; selector.ts export const getProperty = createSelector(getState, f ...

Troubleshooting CSS Issues in ASP.NET Boilerplate

I am attempting to apply a CSS style to a text input similar to the one found on the CreateUser default page. However, I am encountering an issue where the blue line under the textbox does not appear when I navigate away from and then return to the page. ...

Connecting the Telegram web app to Angular is a simple process that involves integrating the

I'm having trouble figuring out how to integrate telegram with angular. In my HTML file, I've included the following - <script src="./assets/telegram-web-app.js"></script> However, I'm unsure of what steps to take in t ...

What is the appropriate event type to pass to the onKeyPressed function in a React application utilizing MaterialUI and written with Typescript?

I am currently working on a React application using Typescript and MaterialUI, where I have implemented a TextField component. My goal is to capture the value of the input HTML element when the user presses the enter key. To achieve this, I have created ...