Angular - Promise的问题无法找到'object'类型的不同支持对象'[object Object]'

时间:2017-08-06 13:34:31

标签: angular rest api promise

我在尝试从API中获取成员时遇到问题。显然请求工作正常,但angular无法将结果提取到成员对象或类似的东西。我真的不明白它引起的错误。

到目前为止,它是一个基本的应用程序,它只是从API中获取成员,并且应该在内联模板中显示它们。

这是我的服务:

import { Headers, Http, Response } from '@angular/http';
import { MEMBERS } from './../member-mock';
import { Member } from './../member';
import { Injectable } from '@angular/core';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class MemberService {
    private apiUrl = '../api/members';
    private headers = new Headers({'Content-Type': 'application/json'});
    constructor(private http: Http){}
    members : Member[] = [];
    getMembers(){
        return this.http.get(this.apiUrl)
        .toPromise()
        .then(response => response.json().data as Member[])
        .catch(this.handleError);
    }
}

我的组件

import { ModalService } from './../Services/modal-service';
import { OrderService } from './../Services/order-service';
import { Member } from './../member';
import { MemberService } from './../Services/member-service';
import { Component } from '@angular/core';

@Component({
  selector: 'member-pane',
  template: `
    <div class='order-pane'>
        <h2>Membres</h2>
        <ul class="">
        <li class="membre" *ngFor="let member of members">
            <b>{{member.prenom}} {{member.nom}}
        </li>
        </ul>
    </div>
  `,
  styleUrls: ['./member-pane.css']
})
export class MemberPaneComponent {
    constructor(private memberService: MemberService) { }

    members = this.memberService.getMembers();
}

它引发了以下我不理解的错误: Error screenshot

最后这是API返回的JSON:

[
    {
        "id": 1086,
        "prenom": "Mick",
        "nom": "Mal",
        "amount": 0,
        "total": 0
    },
    {
        "id": 1087,
        "prenom": "Loic",
        "nom": "Pal",
        "amount": 0,
        "total": 0
    }
]

1 个答案:

答案 0 :(得分:0)

您的回复没有data属性,但是是一个数组,所以您应该按原样返回:

getMembers(){
    return this.http.get(this.apiUrl)
    .toPromise()
    .then(response => response.json() as Member[]) // remove 'data'
    .catch(this.handleError);
}

并更改从以下位置获取数据:

members = this.memberService.getMembers();

this.memberService.getMembers()
  .then(members => this.members = members)