给出Angular 2服务中的以下Typescript:
getLanguages () { return this.http.get(this._languagesUrl) .map(res => <Language[]> res.json().data) .catch(this.handleError);
在我需要从数组中查找特定项目的情况下,我很难使用它.例如,我无法执行以下操作,因为过滤器需要Observable< Language>而不是Observable< Language []>正在归还.
getLanguages().filter(language => language.id == 3) // Error
我感谢我的问题可能是我混合了同步和异步行为,所以我提供了我的用例:用户可以输入语言ID,我想显示相关的语言名称.我想利用带有Observable结果的getLanguages(),因为它已经在项目的其他地方使用了.我还希望实现一些缓存,这样每次进行查找时都不会发出HTTP请求.
有什么想法吗?
以下是您要做的事情的示例:
https://plnkr.co/edit/lK47pVaW8b0CEez0mum4?p=preview
按Chrome中的F12查看日志,以便更清楚地了解正在进行的操作以及为什么它在您的示例中不起作用.
特别注意:
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 ) ); }
这是另一种可能更好的方法:
_langService.getLanguages() .map( list => list.filter(this._filter3rdLanguage) ) //see that this one IS filtered. .do( list => console.log(list) ) .subscribe( list => this.languages = list );