0

need some help, for the life of me I can't get this to work. I'm trying to loop through an array which is within a config value and then trigger another function within the service I created, but I get an error

TypeError: Cannot read property 'registerToken' of undefined

Is there not a better way to do this it feels very clunky?

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) {

  }    

}

3 Answers 3

1

You need to use an arrow function which have the context,

 config.campaigns.forEach((data) => {
        if (campaignToken == data.title) {
          if (data.enabled) {
            this.registerToken(campaignToken);
          }
        }
 });
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome thanks @sajeetharan small things that had me for hours. I see this also seems to work var obj = config.campaigns.find(function (obj) { return obj.title === campaignToken; });
Great if that helped
0

After some investigation I found this to be the best shorthand might be wrong, comments welcome

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) {

  }    

}

Comments

0

Another way of doing it will be passing outer "this" to the forEach function, then the foreach have "this" context defined.

Something like:

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

You can refer the documentation of foreach here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.