[英]Angular 2 - TypeError: Cannot set property 'userId' of undefined
I created a model and in a method when I want to give values the the model's properties, I get this error: TypeError: Cannot set property 'userId' of undefined 我创建了一个模型,并在一个方法中想为模型的属性提供值时,出现以下错误:TypeError:无法设置未定义的属性“ userId”
Here is my Model: 这是我的模特:
export class ApplicationUser {
constructor(
public id: string,
public userId: string
) { }
} }
Here is the method: 方法如下:
public alreadyExists(sub: string) {
let applicationUser: ApplicationUser;
this.applicationUserService.getApplicationUser(sub)
.subscribe(
appUser => applicationUser = appUser,
error => this.errorMessage = <any>error
);
if (applicationUser == null) {
applicationUser.userId = sub;
this.applicationUserService.postApplicationUser(applicationUser)
.subscribe(
error => this.errorMessage = <any>error
);
}
localStorage.setItem('userId', sub);
}
The error appears after this line: applicationUser.userId = sub;
该行之后将显示错误: applicationUser.userId = sub;
What do I have to change/add to don't get this error message? 我必须更改/添加什么才能不收到此错误消息?
Thank You! 谢谢!
There are at least three issues with your code. 您的代码至少存在三个问题。
First you disregard the asynchronous nature of your code, second you try to write to a property of an object that is null and third you pass the error callback as the success callback to your post. 首先,您不理会代码的异步性质,其次,您尝试写入对象的null属性,其次,您将错误回调作为成功回调传递给您的帖子。
I don't know what 'sub' is but you seem to use it as userId so I do as well. 我不知道“ sub”是什么,但您似乎将其用作userId,所以我也是如此。 Here is a replacement suggestion that does what you are trying to do. 这是一个替代建议,可满足您的需求。 Instead of chaining the logic in promises I use the async/await construct. 我没有使用async / await构造,而是在promise中链接逻辑。
public async alreadyExists(sub: string) {
try {
let applicationUser: ApplicationUser =
await this.applicationUserService.getApplicationUser(sub).toPromise();
if (applicationUser === null) {
applicationUser = new ApplicationUser(sub);
await this.applicationUserService.postApplicationUser(applicationUser)
.toPromise();
}
localStorage.setItem('userId', sub);
} catch (error) {
this.errorMessage = error;
}
}
I hope this helps 我希望这有帮助
let applicationUser: ApplicationUser;
The above line will not create the actual object instance here, its just a reference. 上一行不会在此处创建实际的对象实例,而只是创建参考。 Error says applicationUser
is undefined 错误提示applicationUser
未定义
You can try doing 你可以尝试做
let applicationUser: ApplicationUser = new ApplicationUser ('', '');
Alternatively (not tested) 或者(未测试)
let applicationUser: ApplicationUser
applicationUser = Object.create(ApplicationUser.prototype);
this.constructor.apply(applicationUser, ['', '']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.