2016-09-30 160 views
0

我修改了快速入門教程,從以下URL獲取帖子集合:https://jsonplaceholder.typicode.com/posts,但我只能看到默認的初始化值,而不是來自服務器的實際值。Angular2解析HTTP響應

其中一個元件的樣子:

{ 
    "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" 
    } 

該目的被表示爲一個郵政類定義如下:

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

服務返回可觀察到的郵[]

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 || { }; 
    } 

然後,Component訂閱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改爲string,我可以在屏幕上看到100個對象的列表。

+0

您是否嘗試過剛剛返回'body'從'extractData',而不是'body.data '?看[文檔](https://angular.io/docs/ts/latest/guide/server-communication.html#!#parse-to-json)它注意到他們的服務器被設置爲返回值在一個數據對象中,但是*「[n]所有服務器都返回一個帶有數據屬性的對象。」* –

+0

是的,返回body而不是body.data! –

回答

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()); 
    } 
}