2017-01-28 20 views
1

我正在學習Angular2,關於Angular.io的「Tour of Heroes」教程。在教程結尾附近,我們設置了路由到詳細信息頁面並傳遞了一個參數,指示要替換的英雄。這是使用ActivatedRoute中的參數Observable處理的。我們使用switchMap將參數Observable重定向到Promise,以根據參數返回我們實際需要的數據。使用帶有Promises的switchMap

本教程中使用的語法是簡潔的,所以我試圖將其分解爲構建塊以更好地理解正在發生的事情。具體來說,我試圖用實際的功能替換右箭頭符號,我認爲它是相同的。但我的修改不起作用。

下面是代碼:

ngOnInit(): void { 
     this.route.params 
     .switchMap((params: Params) => this.heroService.getHero(+params['id'])) 
     //.switchMap(this.getHero) 
     .subscribe(hero => this.hero = hero); 
    } 

    getHero(params: Params) : Promise<Hero> { 
     return this.heroService.getHero(+params['id']); 
    } 

什麼讓我困惑的是,爲什麼使用目前註釋掉,而不是它上面的線的線,我得到一個錯誤:"Cannot read property 'getHero' of undefined."代碼的兩個版本看上去相同我。

+1

其中之一是一個方法,其他與綁定'this'箭頭功能。你確定它在'.getHero'錯誤,而不是函數內部的'.heroService'? – Bergi

+0

[如何在回調中訪問正確的\'this \'](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) ) – echonax

回答

1

胖箭頭功能保留執行上下文,允許this「變量」與父範圍中的相同。如果您使用.switchMap(this.getHero),則this將指向其他內容,而不是組件。

getHero(params: Params) : Promise<Hero> { 
    // "this" is not what you expect here 
    return this.heroService.getHero(+params['id']); 
} 

所以this.heroService在此處未定義。

0

程式碼中不能使用this.getHero喜歡,因爲

  1. undefined(服務返回Observable,你必須subscribe使用其數據前)
  2. 它不是一個屬性(沒有get modifyer )。
1

你需要bind你的getHero函數。

.switchMap(this.getHero.bind(this)) 

否則您的更改是相同的。像這樣使用綁定可以讓您將getHero作爲獨立函數傳遞給switchMap,而不會丟失this對其的意義。

你可以自己做個實驗:

'use strict'; 
const foo = { 
    bar: 'baz', 
    getBar: function() { 
    return this.bar; 
    } 
}; 

foo.getBar(); 
// => 'baz' 

const myGetBar = foo.getBar; 
myGetBar(); 
// => TypeError: Cannot read property 'bar' of undefined 

const boundGetBar = foo.getBar.bind(foo); 
boundGetBar(); 
// => 'baz' 

const otherObj = { bar: 'hi' }; 
const otherBoundGetBar = foo.getBar.bind(otherObj); 
otherboundGetBar(); 
// => 'hi' 

otherObj.getBar = myGetBar; 
otherObj.getBar(); 
// => 'hi'