Currently, I am exploring a new approach in my Angular2 service that involves using observables. The data source for this service will initially be local storage and later updated when an HTTP call to a database returns. To achieve this dynamic updating of data from various sources, I believe utilizing observables is the way to go. Although I am skipping the local storage aspect for now to focus on understanding the concept, it's essential to mention the rationale behind wanting to implement multiple methods.
My initial plan was to create a "getHTTPEvents()" method that would return an observable containing events fetched from the DB. This setup allows for the potential addition of a 'getLSEvents()' method in the future.
To simulate this functionality, I have the following code snippet:
private eventsUrl = 'app/mock-events.json';
getHTTPEvents(): Observable<Array<any>> {
return this._http.get(this.eventsUrl)
.map(response => response.json()['events'])
.catch(this.handleError); // handle error is a logging method
}
My objective is to develop a method that permits filtering of returned events while still providing an observable to the service users. Here lies my challenge. To address this goal, I'm creating a public method that consumers of the service will utilize (inspired by a pattern found at this resource).
public getEvents(key: string, value: string): Observable<Array<any>> {
var allEventsObserve: Observable<Array<any>> = this.getHTTPEvents();
var filteredEventsObserve: Observable<Array<any>>;
allEventsObserve.subscribe(
events => {
for(var i=0; i < events.length; i++) {
if(events[i][key] == value) {
console.log('MATCH!!!' + events[i][key]); // THIS WORKS!
return new Observable(observer => filteredEventsObserve = observer);
}
}
return allEventsObserve;
},
error => console.error("Error retrieving all events for filtering: " + error));
}
The above implementation does not function as expected. Despite watching tutorials and reading extensively about observables, I've struggled to find resources delving deeper than basic HTTP observables handling.
I also attempted this alternative approach for creating a new observable:
var newObs = Observable.create(function (observer) {
observer.next(events[i]);
observer.complete(events[i]);
});
While this compiles, I am uncertain about how to 'return' it at the appropriate moment. I am unable to create it outside the allEventsObserve.subscribe method due to the absence of 'events,' and returning it within the subscribe seems ineffective. How can I then trigger the 'next' event? Do I need to modify the data within allEventsObserve or generate a new observable with the correct payload - and if so, how do I initiate it?
I consulted resources like this Stack Overflow thread but struggle to grasp how the 'second' observable gets activated. Perhaps my entire approach to this paradigm is flawed?