I'am building upon the tour of heroes from https://angular.io/docs/ts/latest/tutorial/.
The complete tutorial works fine and I've made a nodejs api to handle the backend. At the moment I have a working backend that the tour of heroes frontend can call to retrieve a complete list of heroes, see a hero, update a hero and delete a hero.
My problem is, when I'am trying to add a hero. The nodejs code for doing this looks like this:
function createBox(req, res, next) {
req.body.age = parseInt(req.body.age);
db.none('insert into boxes(name, description)' +
'values(${name}, ${description})',
req.body)
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted one box'
});
})
.catch(function (err) {
return next(err);
});
}
The method in the heroes.component.ts that handles the adding of a hero looks like this:
add(name: string, description: string): void {
name = name.trim();
description = description.trim();
if (!name) { return; }
this.heroService.create(name,description)
.then(hero => {
this.heroes.push(hero);
this.selectedHero = null;
});
}
}
When adding a hero, the array gets populated with one empty item, and the console shows the following error:
EXCEPTION: Error in http://192.168.4.13:3001/app/heroes/heroes.component.html:14:24 caused by: Cannot read property 'id' of undefined
The code around line 14 in the heroes.component.html looks like this:
<ul class="heroes">
<li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}} {{hero.description}}
<button class="delete"(click)="delete(hero); $event.stopPropagation()">x</button>
</li>
</ul>
line 14 is this line:
<span class="badge">{{hero.id}}</span> {{hero.name}} {{hero.description}}
I suspect that the error is due to the fast that the new backend isen't sending the value of the newly created hero back the the client after adding it to the database, as the angular-in-memory-api does it, but I don't know if thats the case. I have been playing around with it for a while without any luck.
Any ideas?
{{hero?.id}}- eko.then(hero => { console.log(hero);..logs? - ekothis.heroService.createservice doesn't return anything.. So ifheroisundefined, you can't expect it to show anything. - eko