为什么在角度教程中我可以在没有传递参数的情况下执行"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

你正在将一个函数作为变量传递给另一个函数。然后,第一个函数最终调用您传递给它的函数。这称为"回调"。查看本教程 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 );    

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

相关内容

最新更新