![](/img/trans.png)
[英]How to call several functions, so they will wait each other in Angular2
[英]Angular2: Calling other functions inside call back functions
我正在構建Angular2應用程序。 我在myService
有一個異步函數deleteObject
。 它返回一個Promise。 我在Component中有另一個函數稱為refresh
,它刷新頁面。 我如何從Promise內部調用刷新。 這是我嘗試的:
export class AppComponent{
refresh(){
// refresh page here
}
delete(){
this.myService.deleteObject(params).then(
function(data){
//this.refresh() doesn't work here.
});
}
}
如果使用Typescript進行編碼,則可以使用粗箭頭功能 。 他們保持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
}
);
}
這是一個上下文問題。 “ this”是指回調函數的上下文,可以是promise或類似的東西。 您真正想要的是對組件上下文的引用,您可以像這樣實現
delete(){
var componentRef = this; // colloquially "that" or "self"
this.myService.deleteObject(params).then(
function(data){
componentRef.refresh() // does work here.
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.