我想旅行,这是我从Angular API中获得的答复。
我从后端得到:
{
"trips": [
{
"id": 0,
"name": "string",
"startDate": "2019-06-30T06:05:48.006Z",
"endDate": "2019-06-30T06:05:48.006Z",
"description": "string",
"roomSharing": true,
"countries": [
{
"id": 0,
"name": "string",
"code": "string"
}
],
"languages": [
{
"id": 0,
"name": "string",
"code": "string"
}
]
}
]
}
这很好,但是我在客户端有问题。 这是我旅行的代码:
getTrips(): Observable<Trip[]> {
return this.http.get<Trip[]>(this.apiUrl + '/Trip/Get')
.pipe(
tap(_ => console.log('fetched trips')),
retry(1),
catchError(this.handleError),
map(data => {
return data;
})
);
}
在我的组件中,我有:
loadTrips() {
return this.rest.getTrips()
.subscribe((data) => {
this.trips = data;
console.log(this.trips);
}
, err => console.log(err));
}
我想用以下模板来旅行:
<div class="card mb-3 trip" *ngFor="let trip of trips">
但我必须喜欢:
<div class="card mb-3 trip" *ngFor="let trip of trips.trips">
所以,问题是我该如何映射我的响应以获取Trip数组而不是Trips数组?
答案 0 :(得分:1)
除非我对某些事情有误解,否则这应该可行:
interface TripsResponse {
trips: Trips[],
}
getTrips(): Observable<Trip[]> {
// use your response interface instead
//return this.http.get<Trip[]>(this.apiUrl + '/Trip/Get')
return this.http.get<TripsResponse>(this.apiUrl + '/Trip/Get')
.pipe(
tap(_ => console.log('fetched trips')),
retry(1),
catchError(this.handleError),
map(data => {
return data.trips; // set it properly here
})
);
}
答案 1 :(得分:1)
不要.map
来使事情复杂化,只需这样做:
loadTrips() {
return this.rest.getTrips()
.subscribe((data) => {
this.trips = data.trips;
}
, err => console.log(err));
}
还要更正您创建的模型Trip[]
export interface ITripsResponse {
trips: Trips[],
}
return this.http.get<ITripsResponse>(this.apiUrl + '/Trip/Get')
否则,通过
更正.map
map((data) => {
return data.trips;
})
然后Observable<Trip[]>
将是有效的返回类型
答案 2 :(得分:1)
更改您的退货单:
return this.http.get('/Trip/Get')
.pipe(
tap(_ => console.log('fetched trips')),
retry(1),
catchError(this.handleError),
map((data: TripsResponse) => { // change made here; make data of type TripsResponse
return data.trips;
})
);
TripsResponse在哪里
interface TripsResponse {
trips: Trips[],
... // other fields for future if required
}