I am not able to map the nested json array from my local mock data. The json data is supposed to be like
{
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: ' '}
]
}
}
The service is
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);
}
}
The component is
carouselList: CarouselData;
ngOnInit():void{
this.indexService.getCarouselList().subscription(response => {
this.carouselList = response;
console.log(response);
})
}
The console log is enter image description here
I can access the json data in the correct form, but when I try to access the array in the list object, I got a undefined error.
The modification in the service file is
getCarouselList(): Observable<CarouselList[]>{
return this.http.get<Carousel>(this.carouselUrl).map(response =>
response.data.list as CarouselList[]);
}
and the corresponding modification in the component is
carouselList: CarouselList[];
ngOnInit():void{
this.indexService.getCarouselList().subscription(response => {
this.carouselList = response;
console.log(response);
})
}
In the final, the console prints a undefinied object instead of printing the array objects of the list. The compiler and browser don't display any error, but I just can't map the sub-array objects in the list. Can you please help me with this?
Thanks