Angular2解析HTTP响应

时间:2016-09-30 17:09:23

标签: javascript json http angular

我修改了快速入门教程,以便从以下网址获取帖子集合:https://jsonplaceholder.typicode.com/posts,但我只看到默认的初始化值,而不是服务器的实际值。

其中一个元素如下:

  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  }

此对象表示为下面定义的Post类:

export class Post
{
    userId: number;
    id: number;
    title: string;
    body: string;
 }

该服务返回Observable of Post []

import { Post } from './post'

@Injectable()
export class PostService{
    private postUrl = 'https://jsonplaceholder.typicode.com/posts';

    constructor (private http: Http) {}

    public getPosts (): Observable<Post[]> {
    return this.http.get(this.postUrl)
                    .map(this.extractData);

    }

    private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
    }

组件订阅Observable以获取数组并设置其属性:

import { Post } from './post'
import { PostService } from './postservice.service'

@Component({
    selector:'mi-comp',
    template: `<h1>Embedded Component</h1>

        <ul>
        <li *ngFor="let post of posts">
        {{post.id }}  {{post.title }} 
        </li>
        </ul>
    `,
    providers: [PostService]
})

export class MiComponente
{
    posts: Post[] =   

     [{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio            reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  }];

    errorMessage: string;
    counter = 0;

    constructor(private postService: PostService){

    this.postService.getPosts()
                            .subscribe(
                            posts => this.posts = posts,
                            error => this.errorMessage = <any>error);   
}

如果我更改服务的提取功能以便返回body.data,我会看到默认值一秒钟,然后为空。我调试了响应,我可以看到那里的100元素数组。

此外,如果我将所有内容从Post更改为字符串,我可以在屏幕上看到100个对象的列表。

1 个答案:

答案 0 :(得分:0)

class MiComponente中,更改为:

import { Component } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
import { PostService } from './postservice.service'

@Component({
    selector:'mi-comp',
    template: `<h1>Embedded Component</h1>
        <ul *ngFor="let post of posts">
          <li>{{post.id }}</li>
          <li>{{post.title }}</li>
          <li>  {{post.body}} </li>
        </ul>`, 
    providers: [PostService]
})

export class MiComponente implements OnInit
{
    posts [];

    errorMessage: string;

    constructor(private postService: PostService){}

    ngOnInit(){
        this.postService.getPosts().subscribe(posts => this.posts = posts, error => this.errorMessage = error); 
    }
}

class PostService中,更改为:

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';  
import 'rxjs/add/operator/map'; 

@Injectable()
export class PostService{
    private postUrl = 'https://jsonplaceholder.typicode.com/posts';

    constructor (private http: Http) {}

    public getPosts (): Observable {
        return this.http.get(this.postUrl).map((response: Response) => response.json());
    }
}