Angular 2 - 带有promise的Http返回Undefined

时间:2016-07-19 13:48:18

标签: angularjs angular angular-promise

我是Angular2的新手,我想从json文件中获取数据。要做到这一点,我使用Http with Promise,但当我从我的promise变量中执行console.log时,它们返回Undefined。

  

post.services.ts

import {Injectable} from '@angular/core';
import { Headers, Http, Response} from '@angular/http'; 
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import {Post} from '../interfaces/post.interface';
@Injectable()
export class PostService{
    private url = 'myjson.json';
    constructor(private http: Http){ }
    private extractData(res: Response) {
      let body = res.json();
      console.log(body.data);
      return body.data || null;
    }
    getPosts(): Promise<Post[]>{
        return this.http.get(this.url)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }   
    private handleError(error: any) {
      console.error('An error occurred', error);
      return Promise.reject(error.message || error);
    }
}
  

posts.component.js

import { Component, OnInit } from '@angular/core';
import { Router }            from '@angular/router';
import {PostService} from '../services/post.service';
import {Post} from '../interfaces/post.interface';

@Component({
    selector: 'posts',
    template: 
    `
    <h1>Posts</h1>
    <form (submit)="addPost()">
        <label for="title">Title</label>
        <input type="text" [(ngModel)]="title" />
        <br />
        <label for="body">Body</label>
        <input type="text" [(ngModel)]="body" />
        <br />
        <input type="submit" value="Submit" />
    </form>
    <ul>
        <li *ngFor="let post of posts">
            {{1+1}}
            <h3>{{post.title}}</h3>
        </li>
    </ul>
    `,
})

export class PostsComponent implements OnInit{
    private posts:Post[];
    private title:string;
    private body:string;
    private newPost:Object;
    error: any;

    constructor(private _postService:PostService){}
    getPosts(){
        this._postService.getPosts().then(posts => this.posts = posts).catch(error => this.error = error);
    }
    ngOnInit() {        
        this.getPosts();
        console.log(this.posts);
    }
    addPost(){
        this.newPost={
            title:this.title,
            body:this.body
        }
    }
}
  

post.interface.ts

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

请有人帮我吗?谢谢。

1 个答案:

答案 0 :(得分:7)

因为promises / HTTP请求是异步的。您需要在HTTP请求的promise的回调中添加console.log。如果你在这个回调之外(即在执行请求之后)那样做,那么响应就不再存在,所以你将有一个未定义的。

以下是一个示例:

getPosts(){
    this._postService.getPosts().then(posts => {
      this.posts = posts;
      console.log(this.posts); // not null
    }).catch(error => this.error = error);
}

ngOnInit() {        
    this.getPosts();
    console.log(this.posts); // null
}

修改

我认为问题出在您的extractData方法中。您不应该使用body.data,除非您的JSON属性中有data属性。

    private extractData(res: Response) {
      let body = res.json();
      console.log(body);
      return body || null; // <-------
    }