Reputation: 251
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
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;
What do I have to change/add to don't get this error message?
Thank You!
Upvotes: 1
Views: 9114
Reputation: 2799
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.
I don't know what 'sub' is but you seem to use it as userId so I do as well. 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.
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
Upvotes: 4
Reputation: 29795
let applicationUser: ApplicationUser;
The above line will not create the actual object instance here, its just a reference. Error says applicationUser
is undefined
You can try doing
let applicationUser: ApplicationUser = new ApplicationUser ('', '');
Alternatively (not tested)
let applicationUser: ApplicationUser
applicationUser = Object.create(ApplicationUser.prototype);
this.constructor.apply(applicationUser, ['', '']);
Upvotes: 2