Ways to retrieve a service variable within a delegated function (callback)

I am currently using a service that has a variable which needs to be updated by the service itself. However, I am facing an issue where I cannot access the variable in anonymous or delegated functions.

(function() {
  'use strict';

  angular
      .module('yoTest')
      .service('mainService', mainService);

  /** @ngInject */
  function mainService($timeout) {
    this.counter = 1;
    this.updateCounter = function updateCounter() {
      this.counter++;
      $timeout(updateCounter, 500);
    }
    this.updateCounter();
  }
})();

Whenever I try to reload the "updateCounter" using $timeout, I encounter an error. Why is this happening?

Is there a way to access it using timeout and delegate/callback methods?

Answer №1

When calling a function, the issue arises when you pass the updateCounter function reference inside the $timeout callback. This causes a problem because when the $timeout tries to evaluate that function, the this within updateCounter will refer to its own context rather than the context of mainService. In such scenarios, it is necessary to explicitly pass the current context using .bind(this).

this.updateCounter = function updateCounter() {
  this.counter++;
  console.log(this.counter)
  $timeout(updateCounter.bind(this), 500);
}

PLuker

The same result can be achieved in ES6 by utilizing a Fat Arrow function.

$timeout(() => { updateCounter () }, 500);

Answer №2

In addition to Pankaj's response, an alternative approach is to store the current context in a variable and access properties and functions through this variable.

function mainService($timeout) {
  var serviceContext = this;

  serviceContext.counter = 1;

  serviceContext.updateCounter = function updateCounter() {
    serviceContext.counter++;
    console.log(serviceContext.counter)
    $timeout(serviceContext.updateCounter, 500);
  }

  serviceContext.updateCounter();

}

http://plnkr.co/edit/EuTiiP8HZUPulmJIX3IP

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

Is it possible to send more than one parameter in a $http.post request

Currently, I am attempting to make a POST request to store data on the server through the specified URL: url = /api/projects/:projectId/scenarios/:scenarioId My objective is to transmit both the projectId and scenarioId. Could someone please advise me on ...

Tips for preventing duplicate entries in an AG Grid component within an Angular application

In an attempt to showcase the child as only 3 columns based on assetCode, I want to display PRN, PRN1, and PRN2. Below is the code for the list component: list.component.ts this.rowData.push( { 'code': 'Machine 1', &apo ...

Is there a way for me to access a user control property directly from the client side?

I'm in the process of developing several user controls that will be derived from my base class, BaseControl, which is a subclass of UserControl. The BaseControl class contains important features that I will need to utilize, including a string property ...

Tips for keeping the header section anchored to the top of the page

I am having trouble getting the menu bar and logo to stick at the top of my header section in the template. I have been trying different solutions, including using the sticky.js plugin for almost 4 days now but it's not working. I also have parallax e ...

Why doesn't ng-init work in AngularJS?

I encountered a parse error Syntax Error: Token '{' is an unexpected token at column 8 of the expression [user= ${user}] starting at [{user}]. home.html <body ng-controller="mainCtrl" ng-init="user= ${user}"> In this instance, I am att ...

Customizing the marker size in Angular OpenLayers

Is there a way to adjust the size of a custom icon image for markers? For example, if I specify the size within the style like this: style: { image: { icon: { anchor: [0.5, 0.5], anchorXUnits: 'fraction', ...

Ensure the browser stays anchored at the bottom of the page while employing jQuery to reveal a div

This piece of code allows me to toggle the visibility of a div: <a href="#" class="show_hide">Show/hide</a> <div class="slidingDiv"> My content...... <a href="#" class="show_hide">hide</a></div> <script src="http:// ...

Utilizing async/await in JavaScript within a class structure

I am facing a dilemma in using the new async/await keywords within the connect method of my JavaScript class. module.exports = class { constructor(url) { if(_.isEmpty(url)) { throw `'url' must be set`; } ...

ReactJS: Trouble encountered while parsing information from JSON data

Currently, I am facing an issue while trying to pass data from my JSON file to my ReactJS application. The error message that I am encountering is as follows: TypeError: Cannot read property 'mainPage' of undefined Upon console.logging siteDa ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...

Outputting messages to a component with React

I'm attempting to create a component similar to a console where messages are displayed one after the other instead of replacing the old message. My goal is to have a component where I can input strings, like in a chatbox, using different parts of my ...

Ways to prevent recurring variables in Twitter bootstrap dialogues

I need assistance with deleting multiple links using ajax: <a id="id-1">link1</a> <a id="id-2">link2</a> <a id="id-3">link2</a> <a id="id-4">link2</a> ... This is the simplified version of my code: $(docum ...

AngularJS uses variables defined by using curly braces like {{"message"}}

I am currently utilizing the following code snippet to monitor route changes: $scope.$on('$routeChangeStart', function (event, toState, toParams, fromState, fromParams) { //content $log.log(toState); } Whenever I print out "toState ...

Error message: Upon refreshing the page, the React Router is unable to read properties of

While developing a recipe application using the Edamam recipe API, everything was functioning smoothly until an issue arose when refreshing the Recipe Detail page. The error occurs specifically when trying to refresh the page with a URL like http://localho ...

Error 404 encountered while attempting to delete a MongoDB document using the combination of Express, Mongoose,

Just starting out with the MEAN stack and I have a question. So far, I've grasped the basics of adding data to mongodb using mongoose, express, and ui-router. However, I'm stuck on how to delete a document. Every time I attempt it, I encounter 40 ...

Issue encountered while incorporating a PHP file into Javascript code

I'm facing a particular issue where I have a PHP file that is supposed to provide me with a JSON object for display in my HTML file. Everything seems to be working fine as I am receiving an output that resembles a JSON object. Here's the PHP file ...

Choosing an element with JavaScript

var displayedImage = document.querySelector('.displayed-img'); var thumbBar = document.querySelector('.thumb-bar'); btn = document.querySelector('button'); var overlay = document.querySelector('.overlay'); /* Itera ...

Ways to eliminate brackets from a string

Currently, I am working on a challenge involving replacing strings using a function that accepts a string and an object of values. This task involves a two-part algorithm: Replacing values within the string that are enclosed in braces. If the value is wi ...

Navigating to User's Specific Info Page using Node.js

Would love some input on my current issue. I have a table featuring a list of users, and my goal is to display user information in detail whenever a user (which corresponds to a row in the table) is clicked. The process involves identifying which user was ...

Process called gulp useref eliminates certain files from the pipeline

Is there a way to exclude the gulp.src file from output? I am aiming to bundle only JavaScript and output .js files, not HTML. The following blocks in base.html are utilized for bundling JavaScript with gulp-useref: <!-- build:js app.core.js --> &l ...