Scope Error: Variable 'Undefined' is Not Defined Outside Function in Angular 2

In one of my methods, I am subscribing to an observable and later need to unsubscribe from it in another method. The subCounter() method is triggered from an initialization function and works correctly.

subCounter() {
  this.fml = this.playerService.counter(this.song).subscribe(data => {
    this.pos = data;
    this.time.position = Math.round(this.pos);
    this.time.dur = this.song.duration - this.time.position;
    this.time.durMinutes = Math.floor(this.time.dur / 60);
    this.time.durSeconds = ('0' + Math.ceil(this.time.dur - this.time.durMinutes * 60)).slice(-2);
    this.time.posMinutes = Math.floor(this.time.position / 60);
    this.time.posSeconds = ('0' + Math.ceil(this.time.position - this.time.posMinutes * 60)).slice(-2);
    this.time.percent = this.time.position / this.song.duration * 100;
  })
  // This works just fine
  console.log(this.fml);
}

However, when I call the touchActivate() function, which contains an unsubscribe method for the variable stored, it throws an error because this.fml.unsubscribe is undefined. Logging this.fml returns an undefined object.

touchActivate() {
  console.log(this.fml);
  this.fml.unsubscribe();
}

At the beginning of my class, I have the variable declared as: public fml: any;

Answer №1

Give this a shot:

When dealing with touch events, you can try the following code snippet: $('.range-slider').on("touchstart", this.touchActivate.bind(this));

An alternative approach is to utilize arrow functions to preserve the context of 'this':

To ensure proper binding of 'this', you can use an arrow function like so: $('.range-slider').on("touchstart", () => this.touchActivate());

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

What makes it impossible to use var instead of let in ngFor?

My understanding is that in JavaScript, we typically use var and let for variable declarations. The main difference between the two is that var is scoped to the current function, while let is scoped to the current block. Therefore, theoretically I should b ...

Initiate a $digest cycle externally

How can I ensure that $digest triggers when calling methods from outside Angular in an application where code is loaded and eval'd at runtime? Considering that these methods may also be called from within Angular, would it be better to expose a separa ...

What is the process for transmitting data in JSON format generated by Python to JavaScript?

Utilizing Python libraries cherrypy and Jinja, my web pages are being served by two Python files: Main.py (responsible for handling web pages) and search.py (containing server-side functions). I have implemented a dynamic dropdown list using JavaScript w ...

Connect the scroll wheel and then proceed to scroll in the usual way

There are two div elements with a height and width of 100%. One has the CSS property top:0px, while the other has top 100%. I have implemented an animation that triggers when the mousewheel is used to scroll from one div to the other. The animation functi ...

Is there a clear definition of behavior when using non-Promise values with Promise.all?

Are the behavior of Promise.all() docs guaranteed in Node when non-Promise values are passed? For example, using Node 6.10.2: Promise.all([1, 2, 3]).then( res => console.log(res) ); In this scenario, it prints [ 1, 2, 3 ], but is it sure that Promis ...

Set the datepicker to automatically show today's date as the default selection

The date picker field is functioning correctly. I just need to adjust it to automatically display today's date by default instead of 1/1/0001. @Html.TextBoxFor(model => model.SelectedDate, new { @class = "jquery_datepicker", @Value = Model.Selecte ...

What is the best way to showcase content based on data hooks?

I am facing an issue where my form is not displaying the desired entry as expected from my code. The goal is to show a message indicating that the phone number entered by the user is already in use and display it as invalid. I have implemented logic to ch ...

jQuery autocomplete feature fails to retrieve suggestions from local text file

I have implemented the code from a Plunker example in an attempt to minimize the number of ajax requests made to the database. The JSON data is being generated correctly and stored in a text file. However, when I try to display autocomplete options, only ...

Struggling with TypeScript Errors while Extending Theme Colors in Material UI React using TypeScript

Just started with typescript and feeling a bit lost, can someone offer some guidance? I'm working on a React project using material-ui with typescript. To add a new color the correct way, it needs to be added to a theme: const theme = createMuiTheme({ ...

Failed installation of Semantic-ui through npm encountered

Encountering an error while attempting to install semantic-ui through npm for a new project. Here are the version details: $ node -v v16.14.0 $ npm -v 8.10.0 $ npm i semantic-ui npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Adding color to characters, digits in an HTML file

Is it possible to individually style each letter, number, and symbol in an HTML document with a unique color? I am interested in creating a text editor that applies specific colors to each glyph for those who have grapheme-color synesthesia. While there ar ...

Repair the masthead background during overscroll

The Dilemma At the top of my webpage, I have a sleek masthead with a captivating background image that scrolls along with the page. However, there is an issue when users overscroll upwards, causing an undesirable white overflow to appear. To rectify this ...

Unable to alphabetically arrange buttons automatically

I am encountering a challenge with automatically sorting buttons alphabetically on my webpage. I am unable to determine the method for sorting these buttons using jquery or javascript, but my goal is to have them sorted automatically when the page loads. I ...

Does the array.sort() method behave in-place when used on Object.keys()?

When utilizing the .sort() method of JavaScript arrays, the array is altered directly and a reference to the array is returned. Object.keys(obj) generates an array with all the keys from object obj. It's important to note that in JavaScript, object ...

Progressive Web App with Vue.js and WordPress Rest API integration

When creating an ecommerce website using Wordpress, I utilized Python for scraping data from other websites to compare prices and bulk upload products through a CSV file. My next goal is to learn Vue and transform the website into a PWA as it will be esse ...

sort the array based on its data type

Recently diving into typescript... I have an array that is a union of typeA[] | typeB[] but I am looking to filter based on the object's type interface TypeA { attribute1: string attribute2: string } interface TypeB { attribute3: string attri ...

Ways to access information from a service prior to making database changes in Angular 2?

Here is my inquiry. I have a component that allows users to click a favorite button. This action updates the "favorite" column in the database. To update this value, I retrieve it from the database using the following steps: - Upon initializing the compon ...

Tips for arranging the items within the slider according to the specified direction (rtl, ltr) in the Owl Carousel slider for Angular

Is there a way to dynamically change the direction of the owl-carousel-o angular slider based on the selected language? Currently, I have set rtl: true in the owl-carousel configuration during initialization. However, when the user switches to a different ...

Transitioning from embedded browser to system browser in a Next.js / React.JS application

I'm currently dealing with an issue on my Next.js payment page and could really use some expertise. Here's the situation at hand: My payment page has a QR code that directs users to the payment page created with Next.js. When users scan this QR ...

Why isn't the Angular directive resolving the dynamic button text variable?

Trying to implement an iPhone-style Toggle Button using CSS in Angular. The issue I am facing is that the dynamic button text variable "{{v1['btn2']}}" is not being evaluated properly the first time, although it works fine with static text. URL ...