Heroes tutorial - added hero not displayed

226 views
Skip to first unread message

norricorp

unread,
Oct 31, 2016, 9:13:26 AM10/31/16
to Angular
Hi,
I have used the heroes tutorial and when using in memory this works.
But if I get the data from an external source eg grails 3 rest api then adding a hero behaves differently.
The hero is added to the database (I can see that via curl) but the listing of heroes has a place holder for the new hero but no text (no id, no name). A manual refresh of the browser shows a completed list with the new hero properly displayed.

The browser console shows

POST http://centos64:8080/heroes   201

EXCEPTION
: Error in ./HeroesComponent class HeroesComponent - inline template:11:23 caused by: self.context.$implicit is undefined
 
ORIGINAL EXCEPTION
: self.context.$implicit is undefined


This is the code for the component

 add(name: string): void {
  name
= name.trim();
 
if (!name) { return; }
 
this.heroService.create(name)
   
.then(hero => {
   
this.heroes.push(hero);
   
this.selectedHero = null;
   
});
 
}


This is the code for the template

<ul class="heroes">
   
<li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
   
<span class="badge">{{hero.id}}</span> {{hero.name}}
   
<button class="delete" (click)="delete(hero); $event.stopPropagation()">x</button>
 
</li>
</ul>

The service is working - it updates the database so I assume that is OK.

Does anyone have any ideas?

Regards,

Sander Elias

unread,
Nov 1, 2016, 8:35:25 AM11/1/16
to Angular
Hi Norricorp,

Plenty of ideas. Some of them might be even useful to some;)

hmm, while thinking about it, that was probably not your real question. I think there is something in your service, but its hard to tell without that code.

Regards
Sander

norricorp

unread,
Nov 1, 2016, 11:22:27 AM11/1/16
to Angular
Hi Sander,
the service code is
create(name: string): Promise<Hero> {
 
return this.http
   
.post(this.heroesUrl, JSON.stringify({name: name}), {headers: this.headers})
   
.toPromise()
   
.then(res => res.json().data)
   
.catch(this.handleError);
 
}

and you were right - it is the service code. I returned res.json().data when I should return res.json() and that now updates the code.
Many thanks for the help.
John


Reply all
Reply to author
Forward
0 new messages