How to find array element by id using Observable in Angular2

I decided to use Observable instead of Http promises.

Here's what my Promise service looked like:

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 get an array of movies, and I find a specific movie from 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 in type 'Movie []'.

Here is what I tried using 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 as in my Promise service?

+7
angular typescript observable rxjs
source share
1 answer

Suppose you should use the map method instead of subscribe , which returns a 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)); } } 

Plunger example

+6
source share

All Articles