I'm using Angular Material datatable that requires a table to display data.
I would convert this JSON data format that backend sends to frontend
[{"text":"HELEO"},{"text":"HELEO"},{"text":"popopo"},{"text":":kjnkjn"},{"text":"jhjh"}]
To this format
[ { text: 'HELEO' },
{ text: 'HELEO' },
{ text: 'popopo' },
{ text: 'jhjh' } ]
Here's my service:
test: nomchamp[];
gettext(): Observable<any> {
return this.http.get<nomchamp[]>(this.url)
.map(res => { console.log(res); return this.test = JSON.parse(res) });
}
In my back-end:
router
.route("/")
.get(function (req, res, err) {
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
// Attach an asynchronous callback to read the data at our posts reference
ref.once("value", function (snapshot) {
var list = [];
snapshot.forEach(function (elem) {
list.push(elem.val());
})
console.log(list);
console.log(JSON.stringify(list))
res.send(list);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
res.status(500).send(errorObject.code);
});
});
I'm using stringify to be able to send data via res.send
Using JSON.parse I get this error :
JSON.parse: unexpected character at line 1 column 2 of the JSON data
Without using parse , data is not printed in my datatable.
The only case where it's working is when I use res.send(res) in back end but what I would is using res.write(JSON.stringify(res));
JSON.parse(thatString)will result in an object that will be similar to the one you require. Perhaps the issue is that you are not getting JSON, but data that is alreadyJSON.parsed - which is why JSON.parse fails - because JSON.parse only accepts strings to parse