I am facing an issue with my Angular component where I have a class that includes common services and functions. While passing some functions as callbacks, the scope is getting lost during execution. Let me demonstrate the problem through the code below:
@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 can we maintain the correct 'this' reference without explicitly passing it as 'ref' or 'self'?