In my Angular 7 project, I am trying to establish a client-side request to the server-side. Below is the structure of the request that needs to be sent.
{
"title" : "Test Title",
"user": {
"id" : 7
},
"category": {
"id" : 2
},
"description" : "test description",
"quantity" : "2"
}
Describing the model class in Angular:
export class SampleRequest {
title: string;
user: { id: number};
category: { id: number};
description: string;
quantity: number;
}
The input data is gathered through Angular Reactive forms. The user Id originates from the JWT token, representing the currently logged-in user. Here is a snippet from the template file 'sample-request.component.html':
<form novalidate [formGroup]="requestForm" (ngSubmit)="onSubmit()">
<p>
<mat-form-field class="form-field-width">
<input matInput placeholder="Title" type="text" formControlName="title" name="title" required>
<mat-error *ngIf="requestForm.get('title').hasError('required')">Title is required</mat-error>
</mat-form-field>
</p>
... Content truncated for brevity ...
</form>
Now moving on to 'sample-request.component.ts' file:
export class SampleRequestComponent implements OnInit {
requestForm: FormGroup;
sampleRequest: SampleRequest;
constructor(private fb: FormBuilder, private userService: UserService, private tokenStorage: TokenStorageService) { }
ngOnInit() {
this.requestForm = this.fb.group({
title : ['', Validators.required],
category : [''],
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;
this.sampleRequest.user.id = this.tokenStorage.getUser().id;
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;
}
);
}
}
I encountered an issue where 'title' came up as undefined during execution.