LStarky LStarky - 1 year ago 90
Javascript Question

Creating new record in Aurelia -- error with JSON encoding?

I'm creating an Aurelia app and it successfully pulls records from an API, edits and saves changes to individual records, and deletes individual records. However, I cannot seem to fix a problem with creating new records.

In calendar.js, I have the function newCalendar() which is called by a form button.

newCalendar() {
this.selectedId = this.error = null;
this.calendar = [];
this.calendar.cal_name_tran = "New Calendar";
this.calendar.cal_name_orig = "Nuevo Calendario";

When I click the button, I get the following text in the console log:

[cal_name_tran: "New Calendar", cal_name_orig: "Nuevo Calendario"]

The text "New Calendar" and "Nuevo Calendario" are successfully bound to the View in the Modal form.

<div class="form-group">
<label class="control-label" for="cal_name_orig">Calendar name</label>
<input type="text" class="form-control" id="cal_name_orig" placeholder="${'Calendar_Example_Name'&t}" value.bind="calendar.cal_name_orig & validate">
<div class="form-group">
<label class="control-label" for="cal_name_tran">Translated name</label>
<input type="text" class="form-control" id="cal_name_tran" value.bind="calendar.cal_name_tran & validate">

However, when I try to save the calendar using the following function, it sends an empty string, same as what is showing up in the second line of the console log (above).

saveCalendar() {
this.httpClient.fetch("/calendar/new", {
method: 'put',
body: json(this.calendar)

Why does
results in an empty array when
shows the values of the array?

Answer Source

Since you want the calendar to contain key-value pairs, you can make it an object (instead of array).

this.calendar = {};

JSON.stringify expects a valid JSON (can be an array then as well). In your example, although you are creating the calendar as an array, you are using it as an object.

If you want it to be an array, you will have to use the push method instead:

this.calendar = [];
this.calendar.push("New Calendar", "Nuevo Calendario");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download