【问题标题】:Having a problem with using RxJS to average out an array of variables in Angular使用 RxJS 平均 Angular 中的变量数组时遇到问题
【发布时间】:2020-01-21 05:40:09
【问题描述】:

我有一个 Firestore 数据库,其中包含以下字段:day、morning、afternoon、night,在此期间一天中的时间是数字用法。 我正在尝试使用此代码来平均每天 morning 等的值(sunday,monday,...)。

import { Subscriber, Observable, from } from 'rxjs';
import { map, filter, toArray, reduce, switchMap, groupBy } from 'rxjs/operators';
import * as _ from 'lodash';

...
groupedData: any = [];
meter:Observable<any>;
meterId: string;

ngOnInit() {
this.meter = this.db.collection('meters').doc(this.meterId).collection('data').valueChanges();

  from(this.meter)
      .groupBy(x => x.day)
      .flatMap(group => group.toArray())
      .map(g => {
        return {
          day: g[2].day, 
          morning: _.sumBy(g, 'morning'), 
          afternoon: _.sumBy(g, 'afternoon'), 
          night: _.sumBy(g, 'night'), 
        }
      })
      .toArray()
      .subscribe(d => this.groupedData = d);
}

我收到Property 'groupBy' does not exist on type 'Observable&lt;any&gt;'.的错误

我想我正试图从早期版本的 Angular/RxJS 代码中调整它,但失败得很惨。我真的很感激任何帮助。谢谢。

【问题讨论】:

    标签: angular google-cloud-firestore rxjs


    【解决方案1】:

    尝试使用pipe,如下例所示:

    import { map } from 'rxjs/operators';
    import { HttpClient } from '@angular/common/http';
    
    export class MyComponent {
      constructor(private http: HttpClient) { }
      getItems() {
        this.http.get('https://example.com/api/items').pipe(map(data => {})).subscribe(result => {
          console.log(result);
        });
      }
    }
    

    您还可以将多个运算符链接为:

    getItems()
    .pipe(
      switchMap(users => from(users)),
      mergeMap(user => forkJoin(getAddresses(user.id), getCompanies(user.id))
                       .pipe(map(data => ({user, addresses: data[0], companies: data[1] })))
      tap(data => data.user.addresses = data.addresses),
      tap(data => data.user.companies = data.companies),
      map(data => data.user),
      toArray()
      )
    )
    

    【讨论】:

    • 我有点困惑这些选项中的任何一个如何回答我的问题。我需要做的不仅仅是映射数据。我可以轻松做到。
    • 我的意思是使用最新的rxjs语法。有时会出现向后兼容性问题。
    猜你喜欢
    • 2018-01-02
    • 2020-05-14
    • 1970-01-01
    • 2010-09-12
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多