I'm using Angular 7 and I need to post a request to the server. Data collected by the Angular reactive form. This is the original structure that needs to achieve.
{
"title" : "Test Title",
"user": {
"id" : 7
},
"category": {
"id" : 2
},
"description" : "test description",
"quantity" : 2
}
And this is the model class.
export class SampleRequest {
title: string;
category: { id: number};
user: { id: number};
description: string;
quantity: number;
}
Then I suggest assigning elements one by one to the SampleRequest object. Because cannot add user Id and category Id directly. If it is wrong, Please mention.
And this is the sample-request.ts class.
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;
}
);
}
}
Then I got the error TypeError: Cannot set property 'id' of undefined. User Id is assigned by the logged-in user Id through JWT token. Category Id is assigned by the reactive form.
user.idis a number in your JSON while you've defined it as a string in the interface andquantityis a string in your JSON while you've defined it as a number in the interface.TokenStorageServiceclass.