2017-06-16 56 views
0

我有一個角度爲4的組件,它有以下方法。_this.parse不是一個函數 - >一個範圍問題?

private parseResponse (response: Response) : Dimension[] { 
    let responseBody : any[] = response.json(); 
    console.log(responseBody); // I see an array of objects here 
    return responseBody.map((x) => this.parseDimension(x)); // (********) 
} 

private parseDimension (dimension) : Dimension { 
    console.log("called"); // <- I never see this in the console 
    let retVal = new Dimension(
     dimension["DimensionCode"], 
     dimension["DimensionLabel"], 
     dimension["DimensionDescription"] 
    ) 
    return retVal } 

,我讀了脂肪箭頭lambda表達式應該保留的上下文。 我得到這個代替

TypeError: _this.parseDimension is not a function at http://localhost:4200/main.bundle.js:222:61 at Array.map (native) at

其中線是指(********)

我也試過一個簡單的拉姆達像前一次(在同一組件),它的工作原理

getDimensions() : Observable<Dimension[]> { 
    return this.http.get(this.endpoint) 
     .map(this.parseResponse) 
} 
+1

能否請您粘貼整個類和如何使用該方法'parseResponse'被調用? –

回答

2

問題是this.parseResponse未綁定到當前上下文,當你做了return this.http.get(this.endpoint) .map(this.parseResponse)

你只需把它包裝一個arrow function裏面,你把它作爲一個回調map前:

getDimensions(): Observable { 
    return this.http.get(this.endpoint).map((params) => this.parseResponse(params)); 
} 
0

在這種情況下,從方法變化納入物業(物業功能)有助於

// instead of 
private parseDimension (dimension) : Dimension { 
    ... 
} 
// this way the scope will be kept as expected 
private parseDimension = (dimension) : Dimension => { 
    ... 
} 

此外,檢查here the difference in generated code

相關問題