Im trying to display a list of item names from a rest api. I call map on the response observable and subscribe to get the parsed items object.
How can I attach the object to the component and display list of item.name on the html template?
import { Component, bootstrap } from 'angular2/angular2'; import { Http, HTTP_PROVIDERS } from 'angular2/http'; @Component({ selector: 'item-app', viewProviders: [HTTP_PROVIDERS], templateUrl: 'app/content.html' }) class ItemsComponent { items: Object; constructor(http: Http) { http.get('http://localhost:3000/api/items') .map(response => response) .subscribe( items => this.items = items ); } }
<ul> <li *ng-for="#item of items"> {{ item.name }} </li> </ul>
I believe the callback in map is a Response
object. If the response is JSON, you need to call
.map(response => response.json())
Once done, if the actual response is an array, your binding should work.
See the http
API example https://angular.io/docs/ts/latest/api/http/Http-class.html
After alpha 46 you have to do something like this to explicitly tell TypeScript that you are dealing with an object of type Response:
this.http.get(url).map((res: Response) => res.json())
.subscribe(res => this.result = res);
I also have a working sample with documentation here: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http http://www.syntaxsuccess.com/angular-2-samples/#/demo/http
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.