我无法从本地模拟数据映射嵌套的json数组。 json数据应该像
{
success: true,
data: {
count: 2,
pageNo: 1,
pageSize: 10,
list: [
{
title: 'title',
subtitle: 'subtitle',
priority: 0,
img: ' ',
url: ' '},
{
title: 'title2',
subtitle: 'subtitle',
priority: 0,
img: ' ',
url: ' '}
]
}
}
服务是
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
interface Carousel {
success: boolean;
data: CarouselData;
}
interface CarouselData {
count: number;
pageNo: number;
pageSize: number;
list: CarouselList[];
}
interface CarouselList {
title: string;
subtitle: string;
priority: number;
img: string;
url: string;
}
@Injectable()
export class IndexService {
private carouselUrl = 'api/carousel';
constructor(private http: HttpClient) { }
getCarouselList(): Observable<CarouselData>{
return this.http.get<Carousel>(this.carouselUrl).map(response =>
response.data as CarouselData);
}
}
该组件
carouselList: CarouselData;
ngOnInit():void{
this.indexService.getCarouselList().subscription(response => {
this.carouselList = response;
console.log(response);
})
}
控制台日志是 enter image description here
我可以以正确的形式访问json数据,但是当我尝试访问列表对象中的数组时,我得到了一个未定义的错误。
服务文件中的修改是
getCarouselList(): Observable<CarouselList[]>{
return this.http.get<Carousel>(this.carouselUrl).map(response =>
response.data.list as CarouselList[]);
}
并且组件中的相应修改是
carouselList: CarouselList[];
ngOnInit():void{
this.indexService.getCarouselList().subscription(response => {
this.carouselList = response;
console.log(response);
})
}
在最后,控制台打印一个未定义的对象,而不是打印列表的数组对象。编译器和浏览器不显示任何错误,但我无法映射列表中的子数组对象。你能帮帮我吗?
由于