Scipion
Scipion

Reputation: 11888

Angular4 referencing a service inside a map operator

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 ?

Upvotes: 1

Views: 61

Answers (2)

J P
J P

Reputation: 1

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

}

Upvotes: 0

nivas
nivas

Reputation: 3186

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)

Upvotes: 1

Related Questions