【问题标题】:ERROR TypeError: Cannot set property 'id' of undefined错误类型错误:无法设置未定义的属性“id”
【发布时间】:2020-08-19 20:20:40
【问题描述】:

我正在使用 Angular 7,我需要向服务器发布请求。由 Angular 响应式表单收集的数据。这是需要实现的原始结构。

{
    "title" : "Test Title",
    "user": {
        "id" : 7
    },
    "category": {
        "id" : 2
    },
    "description" : "test description",
    "quantity" : 2
    
}

这是模型类。

export class SampleRequest {
  title: string;
  category: { id: number};
  user: { id: number};
  description: string;
  quantity: number;
}

然后我建议将元素一一分配给 SampleRequest 对象。因为不能直接添加用户ID和类别ID。如有错误,请指出。

这是 sample-request.ts 类。

  requestForm: FormGroup;
  sampleRequest: SampleRequest = new SampleRequest();
  isSuccessful = false;
  isFailed = false;
  isProgress = false;
  errMsg: string;

  constructor(private fb: FormBuilder, private userService: UserService, private tokenStorage: TokenStorageService) { }

  ngOnInit() {
    this.requestForm = this.fb.group({
      title : ['', Validators.required],
      category : ['',Validators.required],
      description: ['', Validators.required],
      quantity: ['', [Validators.required, Validators.pattern]]
    });

  }



  onSubmit() {
    this.sampleRequest.title = this.requestForm.get('title').value;
    this.sampleRequest.category.id = this.requestForm.get('category').value; //here is the problem
    this.sampleRequest.user.id = this.tokenStorage.getUser().id;  //and here
    this.sampleRequest.description = this.requestForm.get('description').value;
    this.sampleRequest.quantity = this.requestForm.get('quantity').value;
    console.log(this.sampleRequest);
    this.userService.newSampleRequest(this.sampleRequest)
      .subscribe(
        data => {
          this.isSuccessful = true;
          this.isProgress = true;
        },
        error => {
          this.isFailed = true;
          this.isProgress = true;
          this.errMsg = error.error.message;
        }
      );
  }

}

然后我收到错误 TypeError: Cannot set property 'id' of undefined。用户 ID 由登录的用户 ID 通过 JWT 令牌分配。类别 ID 由反应形式分配。

【问题讨论】:

  • 与您的要求无关,但您粘贴的 JSON 数据与您定义的 TS 接口略有不同 - user.id 是您的 JSON 中的一个数字,而您已将其定义为接口中的字符串,quantity 是 JSON 中的字符串,而您已在接口中将其定义为数字。
  • 您可能还应该包含TokenStorageService 类的内容。
  • @Edric 这是一个错误。不过不是那个,我改成数字还是有问题。
  • @Edric TokenStorageService 只返回用户 ID,如 7(作为不带引号的数字)。

标签: json angular typescript angular-reactive-forms


【解决方案1】:

在你的代码中,即使你已经给出了

sampleRequest: SampleRequest = new SampleRequest();

sampleRequest 对象中的其他组件 - 用户和类别仍然是未定义的。

尝试创建一个新的空类别和新的空用户对象并将其设置为 sampleRequest 对象

sampleRequest.category = {};
sampleRequest.user = {};

而且“TypeError: Cannot set property 'id' of undefined”错误应该不会再出现了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 2020-07-22
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多