我正在尝试使用angular的新httpclient从api获取数据,我得到错误属性不存在于IMessage []类型上。如何为以下响应编写接口,
{"data":{"Messages":[{"Id":28,"MessageContent":"test data tsn","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"365@test.com","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message by Dev Team","StyleNumber":null}],"Pagination":{"Page":1,"PageLength":20,"TotalRecords":20,"TotalPages":1},"MessageLimit":{"TotalMessageCount":5,"RemainingMessageCount":3}}}
我在这里尝试了什么,
export interface IMessage {
data: {
Messages: Messages[];
};
}
interface Messages {
id: number;
messageContent: string;
fromUserId: string;
toUserId: string;
productId?: number;
parentMessageId?: number;
subject: string;
styleNumber?: string;
}
我在stackblitz上的code
// Here is the code
import { Component, Input, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { IMessage } from './message.interface';
import { HttpClient, HttpResponse, HttpParams, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit {
constructor (private http: HttpClient) {
console.log('Message repository service instance');
}
readonly ROOT_URL = '//52.70.78.117:7111/api/message';
ngOnInit() {
this.getAllMessages();
}
@Input() name: string;
messages;
getAllMessages(): Observable<IMessage[]> {
this.getAllMessagesFromApi()
.subscribe(data => {
console.log('data is =>', data.data);
this.messages = data;
},
err => {
console.log('Error occured while fetching message List');
});
return;
}
getAllMessagesFromApi(): Observable<IMessage[]> {
return this.http.get<IMessage[]>(`${this.ROOT_URL}/list`);
}
}
答案 0 :(得分:4)
您应该更改getAllMessagesFromAPI()
方法返回IMessage
// method returns type IMessage
getAllMessagesFromApi(): Observable<IMessage> {
// http request returns type IMessage
return this.http.get<IMessage>(`${this.ROOT_URL}/list`);
}
现在您可以访问您的消息数组
.subscribe(data => {
this.messages = data.data.Messages;
},