【发布时间】:2017-04-04 19:25:50
【问题描述】:
我在使用 Typescript 时遇到问题,其中 this 关键字在调试时显示为未定义,因此没有调用我的一些从回调方法调用的私有类方法。我的文本编辑器似乎认为我的参考很好并且给了我智能,所以我认为代码没问题。下面是一个简短的例子。调用 _handleCreationResponse 回调方法时,cacheUser 和 _processSuccessfulRegistration 不会受到影响。
export class User extends Observable {
public email: string;
public password: string;
public username: string
constructor() {
super()
this.email = '';
this.password = '';
this.username = '';
}
public register() {
let user = {
// build out object
}
userService.createAccount(user)
.catch(/* handle error */)
.then(this._handleCreationResponse)
}
private _handleCreationResponse(response) {
let status = response.status;
let userData = response.result;
switch (status) {
case ApiStatus.Success:
this._cacheUser(userData);
this._processSuccessfulRegistration(userData);
break;
case ApiStatus.SomeError:
// handle errors
break;
default:
// do something else
break;
}
}
private _cacheUser(user) {
// handle user caching
}
private _processSuccessfulRegistration() {
// call some other services and
// navigate to a new view
}
}
【问题讨论】: