Hello.
How to parse json in angular 2?
I get a get request for this file: http://jsonplaceholder.typicode.com/posts
I write it to the response variable of the type - string.

If I output {{ response }} , then I get [object Object],[object Object],... If {{ response | json }} {{ response | json }} , I just get the text.

How can I get and display "title" and "body" from it ??

post.component.ts

 import { Input, Component } from '@angular/core'; import { HttpService } from './http.service'; @Component ({ selector: 'news-post', templateUrl: './app/news/post.component.html', inputs: ['posts'], providers: [HttpService] }) export class NewsPostsComponent { response: string; constructor(private _httpService: HttpService) { this._httpService.getPosts() .subscribe( response => this.response = response, error => console.log(error) ); } } 

http.service.ts

 import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/Rx'; @Injectable() export class HttpService{ constructor(private _http: Http){} getPosts(): Observable<any> { return this._http.get('http://jsonplaceholder.typicode.com/posts') .map(res => res.json()); } } 

post.component.html

 <div class="ui main text container"> <h1 class="ui header">Title</h1> <p>Description</p> <hr> </div> 
  • add code, how you get and what you use - Grundy
  • @Grundy added - Roman Kravets 1:14 pm
  • If {{response | json}}, I just get the text. - what did you want to receive? - Grundy
  • @Grundy, so I just wrote - Roman Kravets
  • one
    and you have no objects there, only an array with objects, well, since typescript gives types - it’s better to use them instead of any - Grundy

1 answer 1

 <div class="ui main text container" *ngFor="let nw of response"> <h1 class="ui header">{{ nw.title }}</h1> <p>{{ nw.body }}</p> {{ nw.userId }} <hr> </div>