Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 way to get item from Observable<Xyz[]>

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

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

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.

Any thoughts?

like image 691
gxclarke Avatar asked Feb 11 '16 23:02

gxclarke


People also ask

Why use subject instead of Observable?

Observable can inform only one observer, while Subject can inform multiple observers. for each subscription observable output is diffrent but if you are expecting same output for in diffrent observer recommended to use Subject!

How can Observable objects described as in Angular?

Observable in Angular is a feature that provides support for delivering messages between different parts of your single-page application. This feature is frequently used in Angular because it is responsible for handling multiple values, asynchronous programming in Javascript, and also event handling processes.


1 Answers

finding item in Observable<Type>

    let item: Language;
    langugages. // observable cached data
        .subscribe((items: Language[]) => item = items.find(p => p.id == 3));
like image 191
hadi Avatar answered Nov 05 '22 10:11

hadi