Reputation: 119
I have an observable that contains an array of news article objects that i wish to group by date, so that i can use it in my template.
I've read about the groupBy operator, but i can't get it working yet. I've set up an array that i fill with the items array in my Observable:
export class NewsArchiveComponent implements OnInit {
archivedNews$: Observable<NewsItemPage> | undefined;
newsItems: NewsItem[] = [];
constructor(private newsService: NewsService) { }
ngOnInit(): void {
this.archivedNews$ = this.newsService.newsPerYear();
this.fillNewsArray();
}
fillNewsArray() {
this.archivedNews$?.subscribe(x => {
this.newsItems = x.items;
console.log(x);
console.log(this.newsItems);
});
}
}
I have tried the following to group my items, but it didn't work, neither did it log to console:
groupNewsItems() {
of(this.newsItems)
.pipe(
concatMap(res => res),
groupBy(item => item.publicationdate),
mergeMap(group => zip(of(group.key), group.pipe(toArray())))
)
.subscribe(console.log);
}
Upvotes: 1
Views: 995
Reputation: 12973
Use from
instead of of
and try the following:
import { from, of, zip } from 'rxjs';
import { groupBy, mergeMap, toArray } from 'rxjs/operators';
from(this.newsItems)
.pipe(
concatMap(res => res),
groupBy(
item => item.publicationdate
),
mergeMap(group => zip(of(group.key), group.pipe(toArray())))
)
.subscribe(console.log);
Upvotes: 2