简体   繁体   English

在调用者 scope Typescript 中调用回调 function

[英]Calling callback function in caller scope Typescript

I have an Angular component which have a class consisting of common services and functions.我有一个 Angular 组件,它有一个由常用服务和功能组成的 class。 I am passing some functions as callback while executing them in I am loosing the scope.我在执行它们时将一些函数作为回调传递,我正在丢失 scope。 Below by code I demonstrate the problem下面通过代码我演示了这个问题

@Component({
...
})
export class MyComponent implements OnInit { 
   constructor(private mycommon: MycommonService){}

   private refreshList(){
     console.log("refreshing UI")
   }

   private successCB(data){
     console.log("log success cb:",data);
     console.log("this", this)   //<<<<< ISSUE this is of `MycommonService`
     this.refreshList()  //<<<

     //More Logic and code here ...
   }

   private errorCB(data){
     console.log("log error cb:",data);
   }
       
   //Some user button Action
   update(){
      this.mycommon.saveData("someData", successCB, errorCB)
   }
}



@Injectable()
export class MycommonService {
  public updateAddress(ev: string,successCb: (val: any) => void, errorCb: (val: any) => void) {

    this.http.get(url).subscribe(response => {
      // calling a callback function with data(argument)
       successCb.bind(this)('List retrieved');
    });
  }
}

In Success callback function, how to have a this... Without passing this 'ref' or 'self'Success回调 function 中,如何有一个 this... 不传递这个 'ref' 或 'self'

So, while doing some test I found that while passing a callback function We need to bind this, otherwise this within the callback will point to the caller.所以,在做一些测试的时候我发现在传递一个回调 function 的时候我们需要绑定 this,否则回调中的 this 会指向调用者。

update(){
  this.mycommon.saveData("someData", this.successCB.bind(this), this.errorCB.bind(this))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM