1

Здравствуйте.
Как распарсить json в ангуляр 2?
Я получаю get запросом вот этот файл: http://jsonplaceholder.typicode.com/posts
Записываю его в переменную response типа - string.

Если я вывожу {{ response }}, то получаю [object Object],[object Object],... Если {{ response | json }}, то получаю просто текст.

Как мне с него получать и выводить на страницу "title" и "body"??

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>
13
  • добавляй код, как получаешь и что именно используешь
    – Grundy
    12 окт 2016 в 13:09
  • @Grundy добавил 12 окт 2016 в 13:14
  • Если {{ response | json }}, то получаю просто текст. - а что ты хотел получать?
    – Grundy
    12 окт 2016 в 13:22
  • @Grundy, ну я просто написал 12 окт 2016 в 13:24
  • 1
    а у тебя там нет объектов же, только массив с объектами, ну и раз уж typescript дает типы - лучше их использовать вместо any
    – Grundy
    12 окт 2016 в 13:52

1 ответ 1

0
<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>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.