从Observable< yyz []>获取项目的角度2方法 [英] Angular 2 way to get item from Observable<Xyz[]>

查看:65
本文介绍了从Observable< yyz []>获取项目的角度2方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 2服务中提供以下打字稿:

Given the following Typescript in an Angular 2 service:

getLanguages () {
    return this.http.get(this._languagesUrl)
        .map(res => <Language[]> res.json().data)
        .catch(this.handleError);

在需要从数组中查找特定项目的情况下,我很难使用它.例如,我不能执行以下操作,因为filter期望的是Observable<Language>而不是返回的Observable<Language[]>.

I'm having difficulty using this in circumstances where I need to lookup a specific item from the array. For example, I can't do the following because filter expects an Observable<Language> rather than an the Observable<Language[]> that is being returned.

getLanguages().filter(language => language.id == 3) // Error

我很高兴看到我的问题可能是我混合了同步和异步行为,因此请提供我的用例:用户可以输入语言ID,并且我想显示相关的语言名称.我想在Observable结果中使用getLanguages(),因为它已在项目中的其他地方使用.我还想实现一些缓存,以便每次执行查找时都不会发出HTTP请求.

I appreciate that my issue may be that I'm mixing synchronous and asynchronous behavior, so Ill provide my use case: User can enter a language id and I want to display the associated language name. I want to leverage getLanguages() with the Observable result because it is already being used elsewhere in the project. I also want implement some caching so the HTTP request doesn't get made each time I do a lookup.

有什么想法吗?

推荐答案

以下是您要执行的操作的示例:

Here's an example working of what you want to do:

https://plnkr.co/edit/lK47pVaW8b0CEez0mum4?p=preview

在Chrome中按F12键查看日志,以使您更清楚地了解正在发生的事情以及为什么它在您的示例中不起作用.

Press F12 in chrome to see the logs to give you a more clear idea of what's going on and why it doesn't work in your example.

特别注意:

constructor(private _langService: LanguagesService) {
    _langService.getLanguages() //We get an Observable<Array> object returned.
        //So this is the observable's filter function:
        .filter( this._filter3rdLanguage )
        //The filter gets called only once and its comparing an observable object, not a language object.
        //that's why nothing gets filtered:
        .do( o => console.log(o) )
        //If you filter the actual list instead of the observable object, you'll get it called several times.
        //This is the Array's filter function.
        .subscribe( list => this.languages = list.filter( this._filter3rdLanguage ) );
}

这是另一种可能更好的方法:

This is another, maybe better, way to do it:

  _langService.getLanguages()
    .map( list => list.filter(this._filter3rdLanguage) )
    //see that this one IS filtered.
    .do( list => console.log(list) )
    .subscribe( list => this.languages = list );

这篇关于从Observable&lt; yyz []&gt;获取项目的角度2方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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