1

I have created a service :

@Injectable()
export class AppService {
   constructor(private _convertor: Convertor)

   foo() {
      a = ["1", "2", "3"]
      return a.map(this.blah)
   }

   blah(s: string): number {
     return this_.convertor.parseInt(s)
   }

}

However, it keeps saying that this isn't defined. I replaced my map with a for, and it worked just fine. I also tried to use _.map which gave me the same result. Any idea how to specify to the map what this it is supposed to use ?

Scipion
  • 11,449
  • 19
  • 74
  • 139
  • 2
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Estus Flask Aug 22 '17 at 06:14

2 Answers2

1

current context was lost due to the callback function, From MDN, you can preserve the current context by passing second arg to map function. So,

@Injectable()
export class AppService {
   constructor(private _convertor: Convertor)

   foo() {
      a = ["1", "2", "3"]
      return a.map(this.blah, this)
   }

   blah(s: string): number {
     return this._convertor.parseInt(s)
   }

}

and also it is this._convertor.parseInt(s) but not this_.convertor.parseInt(s)

nivas
  • 3,138
  • 3
  • 16
  • 15
0

Try this.

import { Injectable } from "@angular/core/src/core";
import { Convertor } from "./Convertor"

export class AppService {
    constructor(private _convertor: Convertor)
    {

    }

   foo() {
      let a = ["1", "2", "3"]
      return a.map(this.blah)
   }

   blah(s: string): number {
     return this._convertor.parseInt(s)
   }

}
J P
  • 1