2017-07-02 21 views
0

在角教程中,我有這個爲什麼在角度教程中,我可以做'this.handleError'沒有通過參數?

private heroesUrl = 'api/heroes'; // URL to web api 

constructor(private http: Http) { } 

getHeroes(): Promise<Hero[]> { 
    return this.http.get(this.heroesUrl) 
      .toPromise() 
      .then(response => response.json().data as Hero[]) 
      .catch(this.handleError); 
} 

private handleError(error: any): Promise<any> { 
    console.error('An error occurred', error); // for demo purposes only 
    return Promise.reject(error.message || error); 
} 

我的問題是,如何.catch(this.handleError)作品?

爲什麼我可以做this.handleError沒有通過參數?

+0

其所謂的回調函數。 –

+0

根據文檔(reactivex.io/rxjs/class/es6/...),'catch'方法將函數作爲參數。這個函數需要2個參數(錯誤,被捕獲)。我將'handleError'函數傳遞給「catch」,我的handleError只接收1個參數(錯誤)。如果我將handleError函數更改爲「handleError(error,caught)」,仍然有效。這怎麼可能? –

回答

2

您將一個函數作爲變量傳遞給另一個函數。那第一個函數最終會調用你通過它的函數。這被稱爲「回調」。看看這個教程http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

本質上它是這樣工作的。

var func1 = function(callback) { 
    callback("hello"); 
} 

var func2 = function(text) { 
    console.log(text); // hello 
} 

func1(func2);  
+1

但在這種情況下,catch如何知道必須將參數傳遞給handleError方法? –

+0

這是對發生的事情的一個很好的解釋。絕對是一個難以理解的概念,首先要把你的頭包裹起來...... – jack

+1

不是它知道要傳遞什麼東西,不管它是什麼,它總是傳遞相同的東西。真正重要的是你給它的功能必須知道它得到了什麼。 –

0

Typescript編譯將爲您處理它。 等效代碼看起來

getHeroes(): Promise<Hero[]> { 
    return this.http.get(this.heroesUrl) 
      .toPromise() 
      .then(response => response.json().data as Hero[]) 
      .catch(funtion(error) { 
        console.error('An error occurred', error); 
        return Promise.reject(error.message || error); 
} 

注意:對於理解我單獨編制的catch一部分,而不是全部功能。

但是,如果您要明確指示的說法,你可以按照以下使用,

getHeroes(): Promise<Hero[]> { 
    return this.http.get(this.heroesUrl) 
     .toPromise() 
     .then(response => response.json().data as Hero[]) 
     .catch((response)=> { 
        this.handleError(response); 
     }); 
} 
+0

但是catch如何知道在這種情況下必須傳遞handleError方法的參數? –

+0

根據文檔(reactivex.io/rxjs/class/es6/...),我沒有得到您的問題 – Aravind

+0

,'catch'方法將函數作爲參數。這個函數需要2個參數(錯誤,被捕獲)。我將'handleError'函數傳遞給「catch」,我的handleError只接收1個參數(錯誤)。如果我將handleError函數更改爲「handleError(error,caught)」,仍然有效。這怎麼可能? –

相關問題