Processing a complex object by http get in Angular 6 Processing a complex object by http get in Angular 6 typescript typescript

Processing a complex object by http get in Angular 6


You don't have an array of VideoModels but an array of items in an object. Piping the whole content to a filter lets you filter items out of arrays, but you have an object. You could try the following workaround:

Create an interface like this

interface Item {  date: Date;  text: string;  images: string[];  name: string;  type: string;}export interface VideoModel {  data: {    date: Date;    text: string;    id: number;    items: Item[];  }}

Then you can use HttpClient in your Service as follows

import { Observable } from 'rxjs';import { map, catchError } from 'rxjs/operators';[...]getVideoTape(): Observable<VideoModel> {  return this.http.get<VideoModel>(url).pipe(    map(model => {      const items = model.data.items.filter(item => item.type === 'video');      model.data.items = items;      return model;    }),    catchError(error => console.error(error))  );}

Pay attention to your images array, as it isn't valid json, string[]? Wouldn't it be better to filter the types serverside in order to reduce traffic?


your json data is not valid.

it should be

{"data":{     "date": "2018-02-20 13:10:23",     "text": "tt",     "id": 1,     "items": [            {               "date": "2018-02-20 13:10:23",               "text": "Описание",               "images": [                       "image1.jpg",                       "image2.jpg"                       ],               "name": "Изображения",               "type": "images"               },            {               "date": "2018-02-20 13:10:23",               "text": "Описание",               "image": null,               "type": "video",               "url": "https://www.youtube.com/embed/v64KOxKVLVg"               }            ]     }}

then going to http://json2ts.com/

your model would be

export interface Item {    date: string;    text: string;    images: string[];    name: string;    type: string;    image?: any;    url: string;}export interface Data {    date: string;    text: string;    id: number;    items: Item[];}export interface VideotapeAnswer {    data: Data;}


You say that data is an array of type VideoListModel, the array of cause has no property items. What you did is like Array.items.type which does not make sense. There are probably more fancy solutions but try mapping your result array to an observable where you can use your filters on.

this._subscription2 = this.videoService.getVideoTape().pipe(    map(data => from(data).pipe(filter((d: VideoListModel) => d.items.type === 'video')))    tap(data => data.subscribe(d => {        this.videoTape.push(d);    }))).subscribe();

Additionally map your data like this when using angular version 4+

getVideoTape() {    return this.http.get<VideoListModel[]>(`http://ip_adress/api/v1/mixed_galleries/1`);}