Currently in my Angular 7 project, I am working on posting a request to the server. The data is being collected from an Angular reactive form and needs to follow a specific structure.
{
"title" : "Test Title",
"user": {
"id" : 7
},
"category": {
"id" : 2
},
"description" : "test description",
"quantity" : 2
}
Additionally, here is the model class that corresponds to this structure.
export class SampleRequest {
title: string;
category: { id: number};
user: { id: number};
description: string;
quantity: number;
}
In order to populate the SampleRequest object correctly, it's best to assign each element individually due to limitations with directly adding user Id and category Id. If there are any mistakes in this approach, please let me know.
Moreover, here is the sample-request.ts class I have implemented for handling this process.
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; //encountering an issue here
this.sampleRequest.user.id = this.tokenStorage.getUser().id; //as well as 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;
}
);
}
}
Unfortunately, when testing this implementation, I encountered the error "TypeError: Cannot set property 'id' of undefined." The user Id is meant to be assigned based on the logged-in user's ID retrieved from JWT token, while the category Id should come from the reactive form.