在回调中丢失上下文
Loosing context inside the callback
我有一个服务有这个方法:
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
的线路上,我收到此错误:
ERROR TypeError: Cannot read property 'router' of undefined
我知道这没有定义,但我不确定在回调中使用它的正确方法是什么。
有什么建议吗?
在回调函数外创建对 "this" 的引用。
let outerThis = this;
this.apiService.register(this.user, function(response) {
outerThis.router.navigateByUrl('/login', { state: { registered: true } })
}, function(error) {
console.log(error);
});
两种解决方法:
- ES6 方式:用粗箭头
() => {...}
替换 function() {...}
这样它绑定到 its 词法环境。
ES5 方式:使用.bind 来绑定 这个函数的执行上下文。
this.apiService.register(this.user, function(response) {
this.router.navigateByUrl('/login', { state: { registered: true } })
}.bind(this), function(error) {
console.log(error);
});
我有一个服务有这个方法:
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
的线路上,我收到此错误:
ERROR TypeError: Cannot read property 'router' of undefined
我知道这没有定义,但我不确定在回调中使用它的正确方法是什么。
有什么建议吗?
在回调函数外创建对 "this" 的引用。
let outerThis = this;
this.apiService.register(this.user, function(response) {
outerThis.router.navigateByUrl('/login', { state: { registered: true } })
}, function(error) {
console.log(error);
});
两种解决方法:
- ES6 方式:用粗箭头
() => {...}
替换function() {...}
这样它绑定到 its 词法环境。 ES5 方式:使用.bind 来绑定 这个函数的执行上下文。
this.apiService.register(this.user, function(response) { this.router.navigateByUrl('/login', { state: { registered: true } }) }.bind(this), function(error) { console.log(error); });