【发布时间】: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