I have a mock file containing a collection of Tasks, each of which has a due date. Currently (below) I have the creation of a simple observable that, when subscribed to, returns the collection of mocked Tasks. What I'm failing to figure out is how I can process the flat array of Tasks to group them by their due date, returning a structure like;
// Current data structure (unstructured)
[{due: "2016-01-01"}, {due: "2016-01-01"}, {due: "2016-01-02"}, ...]
// Desired structure for consumption
{
"2016-01-01": [{...}, {...}],
"2016-01-02": [{...}, {...}, {...}],
"2016-01-03": [{...}]
}
My current observable creation code is as follows;
// Service...
tasks: Observable<Task[]>;
// init() called from the constructor
private init() {
this.tasks = Observable.create(observer => {
observer.next(mockTasks);
});
}
getTasks() {
return this.tasks;
}
Which is consumed in my component as follows;
// Component...
ngOnInit() {
this.taskService.getTasks().subscribe(tasks => {
this.tasks = tasks; // Contains the collection of tasks as expected
});
}
This works fine - I get my full array of tasks back as expected. I've tried using the groupBy
operator to achieve the above but the observable created via Observable.create()
does not appear to have that method available. I've been referring to this resource to attempt to achieve this and I notice that Observable.from()
is used instead of .create()
, however this also does not appear to be an available function in my service.
- Is using RxJS operators (such as
groupBy
) the way to go with formatting the data as above (and how can this be achieved)? Or should this be manually formatted? - Regarding either answer to 1 - where should this take place?
Thanks!
Observable.from(mockTasks)
orObservable.of(mockTasks)
. It depends on what output you need, becauseobserver.next(mockTasks)
creates an observable with single array value, not with several object values. There's no desired method available, it should be added manually withimport rxjs/add/observable
andimport rxjs/add/operator
, otherwise you will end up with several basic methods that were initially added by Angular core modules. – Estus Flask