Angular 7: Получить конкретный подобъект в запросе Json - PullRequest
0 голосов
/ 28 февраля 2019

Я хотел бы получить список этих сеансов по сравнению с идентификатором фильма.

Для этого в моем API есть запрос, который позволяет мне получить список сеансов.

JSON Request

{
"seances": [{
  "id": 1,
  "date": "2019-02-25 14:36:54",
  "movie": {
    "id": 1,
    "title": "Stargate : La porte des étoiles",
    "date": "1994-10-27",
    "poster": "Contacté par l'armée américaine, le jeune égyptologue de génie, Daniel Jackson, résout en 1994 l'énigme du gigantesque anneau de pierre et d'acier découvert en 1928 sur le site de la grande pyramide de Gizeh. Cette mission va le projeter à des années-lumière de la Terre chez des extra-terrestres qui ont construit les Pyramides. Un nouveau monde s'ouvre alors ..."
  },
  "room": {
    "id": 1,
    "name": "Super salle",
    "blueprint": "un plan",
    "placenumber": 12,
    "techno": {
      "id": 1,
      "name": "IMAX"
    }
  }
},
{
  "id": 2,
  "date": "2019-02-25 14:36:54",
  "movie": {
    "id": 1,
    "title": "Stargate : La porte des étoiles",
    "date": "1994-10-27",
    "poster": "Contacté par l'armée américaine, le jeune égyptologue de génie, Daniel Jackson, résout en 1994 l'énigme du gigantesque anneau de pierre et d'acier découvert en 1928 sur le site de la grande pyramide de Gizeh. Cette mission va le projeter à des années-lumière de la Terre chez des extra-terrestres qui ont construit les Pyramides. Un nouveau monde s'ouvre alors ..."
  },
  "room": {
    "id": 1,
    "name": "Super salle",
    "blueprint": "un plan",
    "placenumber": 12,
    "techno": {
      "id": 1,
      "name": "IMAX"
    }
  }
},
{
  "id": 3,
  "date": "2019-02-25 14:36:54",
  "movie": {
    "id": 2,
    "title": "Stargate : La porte des étoiles",
    "date": "1994-10-27",
    "poster": "Contacté par l'armée américaine, le jeune égyptologue de génie, Daniel Jackson, résout en 1994 l'énigme du gigantesque anneau de pierre et d'acier découvert en 1928 sur le site de la grande pyramide de Gizeh. Cette mission va le projeter à des années-lumière de la Terre chez des extra-terrestres qui ont construit les Pyramides. Un nouveau monde s'ouvre alors ..."
  },
  "room": {
    "id": 1,
    "name": "Super salle nul",
    "blueprint": "un plan",
    "placenumber": 12,
    "techno": {
      "id": 1,
      "name": "IMAX"
    }
  }
}]
}

Например, я хотел бы получить список сеансов для фильма с id = 1.

IЯ сделал этот код для получения списка сеансов с определенным идентификатором фильма в моем компоненте:

ngOnInit() {
   this.id = this.route.snapshot.params.id;
   this.sceanceService.list().pipe(
      map(model => {
         return model.filter(movies => movies.movie.filter(movieid => movieid.id === this.id));
      })
      ).subscribe(data => {
         this.sceance = data;
   });
}

Подробности этого сервиса SceanceService

export class SceanceService extends ApiService<number, Sceance> {
   constructor(private http: HttpClient) {
      super(http, 'sceances');
   }
}

И детали этого сервиса ApiСервис

export class ApiService<I, T extends Resource<I>> {

  constructor(
    private httpClient: HttpClient,
    private endpoint: string
  ) { }
  list(): Observable<T[]> {
    return this.httpClient.get<T[]>(`${API_BASE_URL}/${this.endpoint}`);
  }

  create(item: T): Observable<T> {
    return this.httpClient
      .post<T>(`${API_BASE_URL}/${this.endpoint}`, item);
  }

  update(item: T): Observable<T> {
    return this.httpClient
      .put<T>(`${API_BASE_URL}/${this.endpoint}/${item.id}`, item);
  }

  get(id: I): Observable<T> {
    return this.httpClient.get<T>(`${API_BASE_URL}/${this.endpoint}/${id}`);
  }

  delete(id: I) {
    return this.httpClient.delete(`${API_BASE_URL}/${this.endpoint}/${id}`);
  }
}

Класс моих моделей

export class Sceance {
    id: number;
    date: Date;
    movie: Movie[] = [];
    room: Room[] = [];
}
export class Movie {
    id: number;
    title: string;
    date: Date;
    poster: string;
}
export class Room {
    id: number;
    name: string;
    blueprint: string;
    placeLenght: number;
    techno: Techno[] = [];
}
export class Techno {
    id: number;
    name: string;
}

Когда я строю свой проект, я получаю этот стек вызовов:

ERROR TypeError: movies.movie.filter is not a function
    at sceance-container.component.ts:25
    at Array.filter (<anonymous>)
    at MapSubscriber.project (sceance-container.component.ts:25)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:35)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (filter.js:38)
    at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber.notifyNext (mergeMap.js:84)

Я не понимаю, почему браузерне доходит до функции фильтра, когда она существует.


У вас есть идеи, откуда может возникнуть проблема?

Знаете ли вы лучший способ для восстановления этого типаинформация?

РЕДАКТИРОВАТЬ

Добавить модель класса

1 Ответ

0 голосов
/ 28 февраля 2019

Ваша модель неверна, seances имеет movie, а не массив movies, и поэтому .filter действительно не является функцией.Вам нужно исправить свой класс Sceance следующим образом.То же самое касается комнаты, ваш пример JSON содержит только одну комнату, а не массив комнат.

export class Sceance {
    id: number;
    date: Date;
    movie: Movie;
    room: Room;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...