Javascript 在回调中释放上下文
我有一项服务采用这种方法:Javascript 在回调中释放上下文,javascript,angular,this,Javascript,Angular,This,我有一项服务采用这种方法: public register(user, successCallback, errorCallback) { const httpHeaders = new HttpHeaders({ 'Content-Type' : 'application/json', }); return this.httpClient.post(`${this.apiURL}/users/register`, user, { observe: 'res
public register(user, successCallback, errorCallback) {
const httpHeaders = new HttpHeaders({
'Content-Type' : 'application/json',
});
return this.httpClient.post(`${this.apiURL}/users/register`, user, { observe: 'response', headers: httpHeaders }).subscribe(
(response) => successCallback(response),
(error) => errorCallback(error)
);
}
我从一个组件调用该服务方法
this.apiService.register(this.user, function(response) {
this.router.navigateByUrl('/login', { state: { registered: true } })
}, function(error) {
console.log(error);
});
在我调用this.router.navigateByUrl的线路上,我收到以下错误:
错误类型错误:无法读取未定义的属性“router”
我知道这没有定义,但我不确定在回调中使用它的正确方式是什么
有什么建议吗?在回调函数之外创建对“this”的引用
let outerThis = this;
this.apiService.register(this.user, function(response) {
outerThis.router.navigateByUrl('/login', { state: { registered: true } })
}, function(error) {
console.log(error);
});
this.apiService.register(this.user, function(response) {
this.router.navigateByUrl('/login', { state: { registered: true } })
}.bind(this), function(error) {
console.log(error);
});
有两种解决方法:
- ES6方法:将
函数(){…}
替换为胖箭头()=>{…}
,这样它就可以绑定到其词汇环境
- ES5方式:使用.bind绑定此函数的执行上下文
let outerThis = this;
this.apiService.register(this.user, function(response) {
outerThis.router.navigateByUrl('/login', { state: { registered: true } })
}, function(error) {
console.log(error);
});
this.apiService.register(this.user, function(response) {
this.router.navigateByUrl('/login', { state: { registered: true } })
}.bind(this), function(error) {
console.log(error);
});
将函数(){…}
替换为胖箭头()=>{…}
,这样它就可以绑定到词法环境。谢谢,这就是解决方案!我知道这件事,但我想避免。无论如何,谢谢你的发帖!