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

前端 未结 1 1727
深忆病人
深忆病人 2021-01-03 22:52

I decided to use Observable instead of Http promises.

That is how my Promise service looked:

export class MovieService {

    movies: Movie[]
    mov         


        
相关标签:
1条回答
  • 2021-01-03 23:21

    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

    0 讨论(0)
提交回复
热议问题