0
我嘗試從API獲取成員時出現問題。顯然,請求正常工作,但角度未能將結果獲取到成員對象或類似的東西。我真的不明白它引發的錯誤。Angular - 具有承諾的問題無法找到類型爲「object」的不同支持對象'[object Object]'
到目前爲止,它是一個基本的應用程序,只需從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
最後這裏是JSON由API返回:
[
{
"id": 1086,
"prenom": "Mick",
"nom": "Mal",
"amount": 0,
"total": 0
},
{
"id": 1087,
"prenom": "Loic",
"nom": "Pal",
"amount": 0,
"total": 0
}
]
還在磨礪我的angular2 +技能,但是這條線擾了我'resp onse => response.json()。data as Member []'。我覺得你正在包裝已經是一個陣列。如果你只有'response => response.json()。data'?這看起來與1.x中的$ http的response.data最接近.. – Brian
另外,我已經將angularjs標記更改爲angular,因爲AngularJS用於1.x straing,而AngularJS用於2+。 (AngularJS:https://stackoverflow.com/tags/angularjs/info),(Angular:https://stackoverflow.com/tags/angular/info)。 – Brian