I have a simple Angular2 application running on my local machine. I am using a service to send an object instance to a webservice API, which then validates the JSON data against a schema. The issue I am facing is that when I try to send the object to the webservice, the ID field is enclosed in quotes, even though it is supposed to be a number according to Typescript.
This problem only occurs when the name
property of the object contains special characters.
I have confirmed that the issue is not with the JSON.stringify method I am using - please refer to the code snippet below.
The application is coded in Typescript.
Unit class:
export class Unit {
id: number;
name: string;
short: string;
triggers_plural: number;
is_headline: boolean;
}
Saving Method:
The following method is used to save an instance of Unit
to the webservice:
updateUnit(unit: Unit): Promise<Unit>
{
var objSend = {unit_data: [unit]}; // Webservice expects an array of units
console.log(objSend.unit_data[0].id === 2); // Returns false even if ID is set as 2
console.log(objToReturn); // Verifies that ID is 2 during testing
return this.http.put(`${this.unitUrl}/${unit.id}`, JSON.stringify(objSend),{headers:this.headers})
.toPromise()
.then(()=> unit)
.catch(this.handleError);
}
When calling this method and having the name
property of the Unit
object containing special characters leads to the ID being treated as a string instead of a number.
Example without special characters (no issue, ID remains a number):
Example WITH special characters (unexpectedly, ID becomes a string):
The updateUnit
method is invoked from the unit-detail component, where unit editing takes place:
export class UnitDetailComponent implements OnInit {
unit: Unit;
constructor(
private unitService: UnitService,
private route: ActivatedRoute
){}
ngOnInit(): void
{
this.route.params.forEach((params: Params) => {
let id = +params['id'];
this.unitService.getUnit(id)
.then(unit => this.unit = unit);
});
}
save(): void
{
this.unitService.updateUnit(this.unit).then(this.goBack);
}
}
The unit.name
input in the template is bound to an input field:
<div *ngIf="unit">
<div>
<label>Edit unit</label>
<div>
<input type="text" [(ngModel)]="unit.name" />
</div>
</div>
<button class="btn btn-default" type="button" (click)="save()">Save</button>
</div>
It is possible that the issue arises during two-way data binding when the name
property is populated by user input in the <input>
, but it is unclear how the id
's type changes?
Link to github repository for the entire project: https://github.com/djoike/ng2-cookbook/tree/master-so