Although I'm not very experienced with Angular, there's a task at my job that requires me to handle it. The task involves a form where users input values and these values are sent directly to the backend for processing. The form is used to submit a PolicyDocument which consists of the following parameters:
import {ContactFrequency} from './ContactFrequency';
export class PolicyDocument {
id: number;
name: string;
description: string;
file: string;
validFrom: string;
country: string;
majorVersion: number;
minorVersion: number;
status: string; // TODO dmann make enum or string set
primaryText: string;
secondaryText: string;
textBlocks: TextBlock[];
contactFrequency?: ContactFrequency;
constructor() {
}
}
The ContactFrequency class looks like this:
export class ContactFrequency{
id:number;
contactFrequency: number;
constructor() {
}
}
And here's how the form collects values:
<label for="inputContactFrequency" class="col-1 col-form-label">Contact Frequency (Days)</label>
<div class="col-2 pr-0">
<input type="number" class="form-control" id="inputContactFrequency" placeholder="(Optional)"
[ngModel]="detail?.contactFrequency?.contactFrequency"
name="contactFrequency.contactFrequency" [disabled]="fieldsDisabled()" min="0"/>
</div>
Apologies for the inconsistent naming convention. My issue is when I input a value, the payload sent to the backend looks like this:
contactFrequency: 180
If no value is inserted, it appears as:
contactFrequency:{
contactFrequency: null
}
It works fine when no value is inserted, but when a value is entered, it does not get passed as an object. Is there a simple way to modify it so that it passes an object to the backend instead?
After filling out and submitting the form, the handleCreate method is triggered:
handleCreate(policyDocument: PolicyDocument) {
this.userFeedbackService.clearAllUserFeedback();
if (this.validatePolicyDocumentDate(policyDocument)) {
this.policyDocumentService.create(policyDocument).subscribe(
(response) => {
console.log('handleCreate returned ', response);
this.router.navigate(['/policies'])
.then(() => this.userFeedbackService.clearAndAddSuccess('Policy created successfully'));
},
() => {
this.removeDefaultValidityInDays();
window.scrollTo({top: 0, behavior: 'smooth'});
});
} else {
window.scrollTo({top: 0, behavior: 'smooth'});
}
}
Subsequently, the process moves on to the service function:
create(policyDocument: PolicyDocument): Observable<PolicyDocument> {
console.log("Policy Document for frequency rule: " + policyDocument);
console.log("Contact Frequency for frequency rule: " + policyDocument.contactFrequency?.contactFrequency);
return this.http
.put(POLICY_DOCUMENTS_API, policyDocument)
.map(data => {
this.userFeedbackService.clearAndAddSuccess('Policy document has been created successfully');
return <PolicyDocument>data;
})
.catch((err) => {
this.userFeedbackService.addError('Failed creating policyDocument');
throw new Error(err.toString());
});
}