简体   繁体   English

Angular 2 HTTP服务不返回承诺

[英]Angular 2 HTTP Service not returning promise

I'm trying to get an angular 2 service to retrieve data from an HTTP request and return it as a promise. 我正在尝试获取角度2服务以从HTTP请求中检索数据并将其作为承诺返回。 When I use the service in the component, the data I'm passing from the service is returned as undefined. 当我在组件中使用该服务时,我从服务传递的数据将返回为undefined。

This is my service 这是我的服务

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

and this is my component 这是我的组成部分

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属性访问。

When you response.json() the result is the exact content from the response of the request you made. 当你response.json() ,结果是你所做请求的响应的确切内容。

In this case, https://jsonplaceholder.typicode.com/posts returns an array (if open the url in a browser you'll see the array): [{...}, {...}, ...] . 在这种情况下, https://jsonplaceholder.typicode.com/posts返回一个数组(如果在浏览器中打开你会看到数组的网址): [{...}, {...}, ...]

From response.json().data remove .data and add || {} response.json().data删除.data并添加|| {} || {} if body is null || {}如果body为null

Finally: 最后:

.then((response: Response) => response.json() || {})

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

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