Angular 2 - TypeError:无法设置属性' userId'未定义的

时间:2017-05-31 11:37:28

标签: angular typescript model undefined

我创建了一个模型,当我想给模型的属性赋值时,我得到了这个错误:TypeError:无法设置属性' userId'未定义的

这是我的模特:

export class ApplicationUser {
    constructor(
        public id: string,
        public userId: string
    ) { }

}

以下是方法:

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);
}

此行后出现错误:applicationUser.userId = sub;

我必须更改/添加哪些内容才能收到此错误消息?

谢谢!

2 个答案:

答案 0 :(得分:4)

您的代码至少存在三个问题。

首先忽略代码的异步性质,然后尝试写入对象的属性为null,第三步将错误回调作为成功回调传递给帖子。

我不知道'sub'是什么,但你似乎将它用作userId,所以我也这样做。这是一个替代建议,可以执行您要执行的操作。我没有在promises中链接逻辑,而是使用async / await构造。

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;
  }
}

我希望这会有所帮助

答案 1 :(得分:1)

let applicationUser: ApplicationUser;

上面这行不会在这里创建实际的对象实例,它只是一个引用。错误说applicationUser未定义

您可以尝试

let applicationUser: ApplicationUser = new ApplicationUser ('', '');

或者(未经测试)

let applicationUser: ApplicationUser
 applicationUser = Object.create(ApplicationUser.prototype);
 this.constructor.apply(applicationUser, ['', '']);