Angular2:在回调函数中调用其他函数
Angular2: Calling other functions inside call back functions
我正在构建 Angular2 应用程序。
我在 myService
中有一个异步函数 deleteObject
。它 returns 一个承诺。我在名为 refresh
的组件中有另一个函数,它刷新页面。我如何从 Promise 内部调用刷新。这是我试过的:
export class AppComponent{
refresh(){
// refresh page here
}
delete(){
this.myService.deleteObject(params).then(
function(data){
//this.refresh() doesn't work here.
});
}
}
这是上下文问题。 "this" 指的是回调函数的上下文,可以是promise之类的。你真正想要的是对组件上下文的引用,你可以像这样实现
delete(){
var componentRef = this; // colloquially "that" or "self"
this.myService.deleteObject(params).then(
function(data){
componentRef.refresh() // does work here.
});
}
如果您使用 Typescript 进行编码,则可以改用 fat arrow functions。它们保留了您所期望的 this
上下文。所以替换
delete(){
this.myService.deleteObject(params).then(
function(data){
//this.refresh() doesn't work here.
});
}
有了这个:
delete(){
this.myService.deleteObject(params).then(
(data)=>{
//this.refresh() should work here
}
);
}
我正在构建 Angular2 应用程序。
我在 myService
中有一个异步函数 deleteObject
。它 returns 一个承诺。我在名为 refresh
的组件中有另一个函数,它刷新页面。我如何从 Promise 内部调用刷新。这是我试过的:
export class AppComponent{
refresh(){
// refresh page here
}
delete(){
this.myService.deleteObject(params).then(
function(data){
//this.refresh() doesn't work here.
});
}
}
这是上下文问题。 "this" 指的是回调函数的上下文,可以是promise之类的。你真正想要的是对组件上下文的引用,你可以像这样实现
delete(){
var componentRef = this; // colloquially "that" or "self"
this.myService.deleteObject(params).then(
function(data){
componentRef.refresh() // does work here.
});
}
如果您使用 Typescript 进行编码,则可以改用 fat arrow functions。它们保留了您所期望的 this
上下文。所以替换
delete(){
this.myService.deleteObject(params).then(
function(data){
//this.refresh() doesn't work here.
});
}
有了这个:
delete(){
this.myService.deleteObject(params).then(
(data)=>{
//this.refresh() should work here
}
);
}