I am trying RESTful service with my Angular2 application.
It is working when I give local json url (/app/config.json)
. But it is not working when I try with below url.
URL : http://localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/get
The above url will return json value as below,
{
"title": "SingerName",
"singer": "Singer123",
"id": "1",
"name": "Hero123"
}
app.module
@NgModule({
declarations: [ AppComponent,HeroListComponent,HeroDetailComponent],
imports: [BrowserModule,HttpModule,routing], bootstrap: [AppComponent]
})
HeroService.ts
getHeroes(){
var headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.request("localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/…) .map((res:Response) => res.json());
}
HeroListComponent
@Component({
selector: 'my-hero-detail',
template: `
<h2>Hero List Component</h2>
<ul *ngFor="let hero of heroes">
{{hero}}
<li>{{hero.id}}</li>
<li>{{hero.name}}</li>
</ul>`
})
export class HeroListComponent implements OnInit {
heroes = [];
constructor(private _heroService:HeroService) {}
ngOnInit(){
this._heroService.getHeroes().
.subscribe(response =>this.heroes = response);
}
}
If what is returned is:
{ "title": "SingerName", "singer": "Singer123", "id": "1", "name": "Hero123" }
This means this is an Object, and not an array you can iterate through in your template.
So maybe change the variable name to just hero, since it's an object and not an array, but this is just a detail ;) Here I'll use heroes
though:
ngOnInit(){
this._heroService.getHeroes().
subscribe(response => this.heroes = response);
}
Then you do not need to iterate the response, just display it like so:
<div>
{{heroes?.id}}
{{heroes?.name}}
</div>
And it's useful to use the safe navigation operator :)
Hope this helps!