"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

Tips for monitoring server response in Angular 2

I received a reply in postman from my PHP code that looks like this: { "error_code": 0, "message": "Inserted Successfully.", "msg": "Inserted successfully." } Here is my Angular code: onSubmit(form:any){ var headers = new Headers(); ...

Searching with Mat-autocomplete across multiple fields simultaneously

I am struggling with a mat-autocomplete that contains 5000 objects, each consisting of a first name and a last name. My goal is to search for both the first name and last name simultaneously regardless of the input order. Currently, I can only search one ...

Encountered an error while trying to access the 'touched' property of undefined within Angular6 reactive forms

When attempting to validate my page, I encountered an error stating 'Cannot read property 'touched' of undefined'. Can someone please assist me with this code? Also, feel free to correct any mistakes you may find. Here is the HTML code ...

What is the process for setting up a signup and sign-in page in Angular 12 while incorporating local storage for authentication?

After saving signup data using local storage, I am now looking to utilize that information on the login page for user authentication. What specific code should be implemented on the login page in order to verify whether the individual has signed up or no ...

How to update the tsconfig.json file within a VS2019 project using MSBuild?

I am working with a Visual Studio solution that contains multiple tsconfig.json files and I would like them to have different behaviors in production. My plan is to create two additional files for this purpose: tsconfig.json will contain the default sett ...

What is the best way to retrieve the URL query parameters in a Node.js environment?

How can I retrieve URL query parameters in Node.js using TypeScript? Below is my attempted code: /** * My Server app */ import * as Http from "http"; import * as url from "url"; import { HttpServer } from "./HttpServer"; import { TaxCalculator } from ". ...

Link the Angular Material Table to a basic array

Currently facing a challenge with the Angular Material table implementation. Struggling to comprehend everything... I am looking to link my AngularApp with a robot that sends me information in a "datas" array. To display my array, I utilized the following ...

What methods can I use to analyze the integrity of the data's structure?

Currently working on an API using NestJS and typeorm. I am in need of a way to verify the format of the data being returned to clients who make requests to it. For instance, when accessing the /players route, I expect the data to have a specific structure ...

Attempting to categorize JSON object elements into separate arrays dynamically depending on their values

Here's the JSON data I'm currently working with: ?$where=camis%20=%2230112340%22 I plan to dynamically generate queries using different datasets, so the information will vary. My main objective is to categorize elements within this array into ...

Bringing in TypeScript definitions for gridster

After starting a new ionic project, I decided to include the gridster.js library by running npm install gridster and npm install @types/jquery.gridster in the root directory of my project. However, when trying to import the installed definitions, I encount ...

Angular findIndex troubleshooting: solutions and tips

INFORMATION = { code: 'no1', name: 'Room 1', room: { id: 'num1', class: 'school 1' } }; DATABASE = [{ code: 'no1', name: 'Room 1', room: { id: 'num1', ...

Issue with running gulp ser on first attempt in SPFX

Every time I try running gulp serve, I encounter the following issue: Error: Unable to locate module '@rushstack/module-minifier-plugin' Please assist me with this problem. Thank you! ...

clicking a table row will activate the *ngFor directive

Incorporating data from an API into a table, I have enabled the functionality for users to click on table rows in order to change the displayed data using background code: <tr [ngClass]="tablerowClass" *ngFor="let dataObject of data$ | async" (click)=" ...

Why is my root page not dynamic in Next.js 13?

I am currently working on a website using Next.js version 13.0. After running the next build command, I noticed that all pages are functioning properly except for the root page. The issue is that it's being generated as a static page instead of dynami ...

Working with an array of objects with varying shapes and validating them

I have dedicated quite a bit of time to this task and would greatly appreciate some assistance. I am in need of a component (a function) that can accept an array of objects while also validating the properties of these objects. Here are the interfaces and ...

Typescript implementation for a website featuring a single overarching file alongside separate files for each individual webpage

Although I've never ventured into the realm of Typescript before, I am intrigued by its concept of "stricter JS". My knowledge on the subject is currently very limited as I am just starting to experiment with it. Essentially, I have developed my own ...

Combining React Context and Typescript using a Custom Hook

I have been working on a context provider in React and Chakra-UI, but I seem to be facing some issues: import { useBoolean } from "@chakra-ui/react" import { createContext } from "react" const MobileContext = createContext<typeof us ...

Restricting enum type to only one member

enum Value { First, Second, } interface Data { value: Value number: number } interface SubData { value: Value.Second } function calculation(input: SubData){ return; } function initiate(){ const input : Data = { numbe ...

Capacitor - Error: Trying to access the property 'getToken' on an undefined object

Currently, I am in the process of integrating notifications using the Capacitor FCM plugin in my Android application. However, upon executing the code below in Android Studio, I encountered this error: "TypeError: Cannot read property 'getToken' ...

Should the PHP interface be exported to a Typescript interface, or should it be vice versa?

As I delve into Typescript, I find myself coding backend in PHP for my current contract. In recent projects, I have created Typescript interfaces for the AJAX responses generated by my backend code. This ensures clarity for the frontend developer, whether ...