如何在Angular2中使用Observable通过id查找数组的元素 [英] How to find an element of an array by id with Observable in Angular2

查看:20
本文介绍了如何在Angular2中使用Observable通过id查找数组的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定使用 Observable 而不是 Http promises.

I decided to use Observable instead of Http promises.

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

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

    }

}

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

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[]'.

这是我尝试使用 Observable 服务的方法:

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

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

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

推荐答案

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

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 示例

这篇关于如何在Angular2中使用Observable通过id查找数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆