Angular 2 HTTP服务未返回Promise [英] Angular 2 HTTP Service not returning promise

查看:67
本文介绍了Angular 2 HTTP服务未返回Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取angular 2服务来从HTTP请求中检索数据并将其返回为Promise.当我在组件中使用该服务时,我从该服务传递的数据将作为未定义返回.

I'm trying to get an angular 2 service to retrieve data from an HTTP request and return it as a promise. When I use the service in the component, the data I'm passing from the service is returned as undefined.

这是我的服务

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

@Injectable()

export class RecordService {
  constructor(private http: Http) {}
  getPosts(): Promise<any> {
    return this.http
      .get('https://jsonplaceholder.typicode.com/posts')
      .toPromise()
      .then((response: Response) => response.json().data)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    console.log('ERROR');
    return Promise.reject(error.message || error);
  }
}

这是我的组成部分

import { Component, OnInit } from '@angular/core';
import { RecordService } from './record.service';
import { Router } from '@angular/router';

@Component({
    selector: 'record-view',
    template: '<h1>This is the record creation page</h1>',
    providers: [RecordService]
})

export class RecordComponent implements OnInit{
    message: string;
    error: any;

    constructor(private recordService: RecordService) { 

    }

    ngOnInit() {
        this.recordService.getPosts()
            .then(data => console.log(data))
            .catch(error => console.log(error));
    }
}

有什么想法为什么数据不确定?

Any ideas why the data would be undefined?

推荐答案

response.json()已经以JSON的形式返回了响应的数据对象,因此请删除.data属性访问权限.

response.json() already gives you back the data object of your response as JSON, so remove the .data property access.

这篇关于Angular 2 HTTP服务未返回Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆