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?
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!
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.
finding item in Observable<Type>
let item: Language;
langugages. // observable cached data
.subscribe((items: Language[]) => item = items.find(p => p.id == 3));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With