简体   繁体   English

Angular2解析HTTP响应

[英]Angular2 parsing HTTP response

I have modified the quickstart tutorial to get a collection of Posts from the following URL: https://jsonplaceholder.typicode.com/posts , but I only see the default initialization values, not the actual values from the server. 我已经修改了快速入门教程,可以从以下URL获取帖子的集合: https : //jsonplaceholder.typicode.com/posts ,但是我只看到默认的初始化值,而不是服务器上的实际值。

One of the elements looks like: 元素之一如下所示:

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

This object is represented as a Post class defined below: 该对象表示为以下定义的Post类:

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

The service returns an Observable of Post[] 服务返回Post []的Observable

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

And the Component subscribes to the Observable to obtain the array and set its attribute: 组件订阅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);   
}

If I change the extract function of the service so as to return body.data, I see the default values for one second, and then empty. 如果更改服务的提取功能以便返回body.data,我会看到默认值一秒钟,然后为空。 I have debugged the response and I can see the 100 element array there. 我已经调试了响应,并且可以在其中看到100个元素的数组。

Additionally, if I change everything from Post to string, I can see a list of 100 objects on the screen. 此外,如果我将所有内容从“发布”更改为“字符串”,则可以在屏幕上看到100个对象的列表。

In class MiComponente , change to this: 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); 
    }
}

In class PostService , change to this: 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());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM