2017-08-22 9 views
1

内のサービスを参照して、私はサービスを作成しました:Angular4が地図オペレータ

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

} 

はしかし、それはthisが定義されていないことを言って続けています。 mapforに置き換えました。うまくいきました。私は同じ結果をもたらした_.mapを使ってみました。 どのように使用する予定ですかthis何を地図に指定するか?

+2

可能性のある重複した[コールバックの内側に正しい\ 'この\'を利用するには?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-コールバック内) – estus

答えて

1

コールバック関数によって現在のコンテキストが失われました。​​から、マップ関数に2番目の引数を渡して現在のコンテキストを保持できます。だから、

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

} 

ともそれがthis._convertor.parseInt(s)なくthis_.convertor.parseInt(s)

0

であるが、これを試してみてください。

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

}