如何在Angular2中通过Observable通过id查找数组的元素 [英] How to find an element of an array by id with Observable in Angular2
问题描述
我决定使用Observable代替Http Promise.
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));
}
}
如何在Promise服务中实现与Observable服务相同的功能?
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 Example
这篇关于如何在Angular2中通过Observable通过id查找数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!