【问题标题】:RXJS Groupby on Observable / ArrayRXJS Groupby on Observable / Array
【发布时间】:2021-06-21 12:59:34
【问题描述】:

我有一个 observable,其中包含我希望按日期分组的新闻文章对象数组,以便我可以在我的模板中使用它。

我已阅读有关 groupBy 运算符的信息,但我还不能让它工作。我已经设置了一个数组,用我的 Observable 中的 items 数组填充:

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

我尝试了以下方法来对我的项目进行分组,但没有成功,也没有登录到控制台:

groupNewsItems() {
    of(this.newsItems)
      .pipe(
        concatMap(res => res),
        groupBy(item => item.publicationdate),
        mergeMap(group => zip(of(group.key), group.pipe(toArray())))
      )
      .subscribe(console.log);
  }

【问题讨论】:

    标签: angular typescript rxjs observable


    【解决方案1】:

    使用from 代替of 并尝试以下操作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-24
      • 2018-11-09
      • 1970-01-01
      • 2017-03-16
      • 2020-11-17
      • 1970-01-01
      • 2019-04-07
      • 2017-12-13
      相关资源
      最近更新 更多