How to find an element of an array by id with Observable in Angular2

早过忘川 提交于 2020-01-03 06:58:13

问题


I decided to use Observable instead of Http promises.

That is how my Promise service looked:

export class MovieService {

    movies: Movie[]
    movie: Movie;
    constructor(private http:Http) { }

   getMovies(): Promise<Movie[]>{

        return this.http.get('http://api.request.com')
            .toPromise()
            .then((res:Response) => res.json()['results'])

    }
    getMovie(id: number): Promise<Movie> {
        return this.getMovies()
            .then(movies => movies.find(movie => movie.id == id));

    }

}

First I fetch an array of movies, and than I find a certain movie of the array by id. However when I try to do the same with Observable, I get an error notification on find: Property 'find' does not exist on type 'Movie[]'.

Here is what I tried with the Observable service:

export class MovieService {

    movies: Movie[];
    movie: Movie;

    constructor(private http: Http) {
    }

    getMovies(): Observable<Movie[]> {

        return this.http.get('http://api.request.com)
            .map((res: Response) => res.json()['results']);
    }

    getMovie(id: number): Observable<Movie> {
        return this.getMovies()
            .subscribe(movies => movies.find(movie => movie.id == id));
    }
}

How can I achieve the same functionality in my Observable service just like in my Promise service?


回答1:


I suppose you should use map method instead of subscribe which returns Subscription object

export class MovieService {
  movies: Movie[];
  movie: Movie;

  constructor(private http: Http) {}

  getMovies(): Observable<Movie[]> {
    return this.http.get('http://api.request.com')
      .map((res: Response) => res.json()['results']);
  }

  getMovie(id: number): Observable<Movie> {
    return this.getMovies()
      .map(movies => movies.find(movie => movie.id == id));
  }
}

Plunker Example



来源:https://stackoverflow.com/questions/40495483/how-to-find-an-element-of-an-array-by-id-with-observable-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!