1

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>

2 Answers2

1

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

Chandermani
  • 42,589
  • 12
  • 85
  • 88
  • If I add .json() , I get this: ' error TS2339: Property 'json' does not exist on type '{}' ' [Same error is mentioned here.](http://stackoverflow.com/questions/33919710/property-json-does-not-exist-on-type) The response should already be json data, so perhaps the json() is unnecessary.. –  Nov 27 '15 at 18:04
  • You have to convert your response to json, the response is returning raw text (assuming is text, could be binary, or whatever), so you need it. In future releases (who knows when) this will be as simple as [`http.get(...).json()`](https://github.com/angular/angular/issues/5211) – Eric Martinez Nov 27 '15 at 23:13
1

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

TGH
  • 38,769
  • 12
  • 102
  • 135