我正在尝试获取 Angular 2 服务以从 HTTP 请求中检索数据并将其作为 promise 返回。当我在组件中使用该服务时,我从该服务传递的数据返回为未定义。
这是我的服务
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));
}
}
知道为什么数据会是未定义的吗?
最佳答案
response.json() 已经以 JSON 形式返回响应的数据对象,因此删除 .data 属性访问权限。
关于javascript - Angular 2 HTTP 服务不返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40009397/