如何在Angular2中使用带有Observable的id查找数组的元素

时间:2016-11-08 20:05:42

标签: angular typescript rxjs observable

我决定使用Observable而不是Http承诺。

这就是我的Promise服务的样子:

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));

    }

}

首先我获取一组电影,而不是通过id找到某个电影的某个电影。但是,当我尝试对Observable执行相同操作时,我收到有关find的错误通知:属性'find'在类型'Movie []'上不存在。

以下是我尝试使用Observable服务的内容:

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));
    }
}

如何在我的Observable服务中实现与Promise服务相同的功能?

1 个答案:

答案 0 :(得分:16)

我想您应该使用map方法而不是subscribe方法返回Subscription对象

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