Unable to locate function in same Service using AngularJS foreach loop

Looking for some assistance as I'm struggling to make this work. My goal is to iterate through an array nested within a config value and then call another function from the service that I built. However, I keep encountering an error:

TypeError: Cannot read property 'registerToken' of undefined

Is there a more efficient way to approach this? The current method seems quite cumbersome.

CampaignService.ts

import { ServerConfig } from "../core/ServerConfig";

declare var config: ServerConfig;

export class CampaignService {
  static $inject = ["localStorageService"];

  constructor(
    public localStorageService: angular.local.storage.ILocalStorageService
  ) {

  }             

  launchCampaign(campaignToken: string) {
    if (campaignToken) {
      config.campaigns.forEach(function (data) {
        if (campaignToken == data.title) {
          if (data.enabled) {
            this.registerToken(campaignToken);
          }
        }
      });
    }
  };

  registerToken(campaignToken: string) {

  }    

}

Answer №1

To solve this issue, you should utilize an arrow function that has access to the context.

 config.campaigns.forEach((data) => {
        if (campaignToken == data.title) {
          if (data.enabled) {
            this.registerToken(campaignToken);
          }
        }
 });

Answer №2

Upon thorough investigation, I have concluded that this particular shorthand method appears to be the most effective. Any feedback or comments on this are appreciated.

import { ServerConfig } from "../core/ServerConfig";

declare var config: ServerConfig;

export class CampaignService {
  static $inject = ["localStorageService"];

  constructor(
    public localStorageService: angular.local.storage.ILocalStorageService
  ) {

  }             

  launchCampaign(campaignToken: string) {
    if (campaignToken) {
       (config.campaigns.find(function (obj) { return obj.title === campaignToken; })) ? this.registerToken(campaignToken) : void (0);
    }
  };

  registerToken(campaignToken: string) {

  }    

}

Answer №3

One alternative method is to pass the outer "this" as a parameter to the forEach function, allowing the forEach to have the correct "this" context.

For example:

config.campaigns.forEach(function (data) {
    if (campaignToken == data.title) {
      if (data.enabled) {
        this.registerToken(campaignToken);
      }
    }
}, this);

You can find more information about forEach in the documentation here.

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

The condition is not functioning properly when the array's length is greater than 1

Within the primary controller, there is an if-else statement: var entity = shareDataService.getModalEntity(); if (entity = "NULL" || entity.length === 1) { myDataPromise = getDataService.getDataFromREST(security); console.log("HERE") } else { ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

Issues with the functionality of the ZeroClipboard Angular plugin

"> I'm fairly new to Angular and currently experimenting with a module called ZeroClipboard. I've made adjustments to my application in order to incorporate the module and configured it as per the demonstration. var app = angular.module ...

Tips for Simplifying Complex Switch Cases with Object Literals in TypeScript

I have a unique situation where I need to switch between two functions within an object literal. One function takes two numerical arguments, "A" and "B", while the other function only takes a single string argument, "C". My TypeScript code showcases my di ...

Analyzing a series of data entries with the possibility of having an empty list

When parsing an array of items using the Sprache library for C#, my code looks like this: public static Parser<string> Array = from open in OpenBrackets.Named("open bracket") from items in Literal.Or(Identifier).Or(Array).DelimitedBy(Comma). ...

What is the best way to display the elements within a two-dimensional character array?

I'm having trouble printing an array of characters in C. I want to print: #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char def[3][10]; //define a multidimensional array of characters strcpy(def[0 ...

Having trouble implementing the 'cursor: pointer' hover effect using JSS in a React Typescript project

I'm attempting to incorporate a simple hover effect (browser standard cursor pointer behavior) into an existing React-Typescript project. After exploring various methods to achieve this, as React doesn't natively support CSS hover styles with in ...

How to use TypeScript to print a blob (PDF) in Internet Explorer or Microsoft Edge?

I need to print a pdf blob using typescript. I've tried the following code, which works in Chrome but not in Edge. Code 1 (works in Chrome but prints blank in Edge) - const fileURL = URL.createObjectURL(blob); const iframe = document.createE ...

Updating certain fields in AngularJS with fresh data

I am facing a challenge with the following code snippet: <div ng-controller="postsController"> <div id = "post_id_{{post.postid}}" class = "post" ng-repeat="post in posts"> ...... <div class="comments"> < ...

Alter the typography of the text that has been enhanced by Google

I am attempting to modify the default font of certain text that is processed through google-code-prettify within an angular directive. The structure of the template served by my directive appears as follows: <pre class= "prettyprint" style= "border:1p ...

Create a new FetchEvent instance within Jest specifically for a Cloudflare Worker deployment

The TypeScript template repository for Cloudflare Workers includes a test that mocks a GET request by instantiating the Request to simulate the input parameters for the handleRequest function. After some modifications to the template, I now pass the raw F ...

What are the steps to utilize the Angular package within NodeJS and Express?

After installing the Angular package through npm install for my Express project, I am feeling a bit lost on how to actually use it. Can someone explain how to properly implement Angular after installing it this way? Alternatively, is the only way to util ...

No data stored in Angular service array

I am facing an issue with storing JSON data in a shared array within a service. The problem arises when I try to update the array with new content, as it seems that clearing the array before loading new data doesn't work properly. Here is how my serv ...

Searching and extracting PHP arrays in a smart way

I have an array structured like this Array ( [id] => 1 [did] => 1 [title] => first link [link] => link.com ) Array ( [did] => 1 [title] => second link [link] => link2.com ) Array ( [id] => 2 [did] => 2 [title] => forum 1 [l ...

Looking to include "none" as an option in a multi-select dropdown menu?

Currently, I am utilizing chosen.jquery.js for a select field. <select chosen multiple data-placeholder="Select Body Part(s)" ng-options="option.Name as option.Name for option in BodyPartList" ng-model="Body_Part"> <option value="" disabl ...

Understanding how objects are created using the reduce method

I'm curious about how the reduce function can transform an array into an object as shown in this example, particularly with the line: p[c[0]] = c[1]; Is this an unconventional syntax for creating key-value pairs that I haven't encountered before ...

The installation of Protractor using `sudo npm install -g protractor` on Mac resulted

Encountered an error when running sudo npm install -g protractor, seems like the folder/files are missing. Any suggestions on how to resolve this issue? Thank you in advance :) npm ERR! Darwin 15.6.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm ...

What could be causing Typescript to inaccurately infer the type of an array element?

My issue revolves around the object named RollingStockSelectorParams, which includes arrays. I am attempting to have TypeScript automatically determine the type of elements within the specified array additionalRsParams[title]. The main question: why does ...

Two selection options controlling filters. The first choice influences the data shown in the second filter

I've been struggling for hours to figure out how to build this functionality. My code seems to be getting close, but I'm having trouble passing my selection from the HTML back to the controller. Here's my Angular code: var Categories = Pa ...

Leveraging Bootstrap within an Angular 17 project

What is the process to integrate Bootstrap into an Angular-17 application using CLI? I attempted to install Bootstrap globally by running npm install -g bootstrap and then added necessary lines in angular.json under style and script. "node_modules/bo ...