5

我有一个Observable<Recipe[]>我想简化为不同类的数组ChartData[]以用作高图(列和饼图)的数据源。

我正在尝试使用 RxJS 管道运算Observable<Recipe[]>符对我的数据调用 reduce 运算符,但我无法让它工作?reduce操作员不会在我的以下项目中迭代它们是Observable<Recipe[]>我的尝试:

this.foodService.getAllReceipes()
  .pipe(
    reduce((array: ChartData[], value: Recipe[], i: number) => {
        const author = this.createOrFindAuthor(array, value[i]);
        author.y += 1;

        return array;
      }, new Array<ChartData>())
  )
  .subscribe(data => this.chartData$ = of(data.sort((a, b) => b.y - a.y)));
}

getAllRecipes()返回Observable<Recipe[]>

this.chartData$Observable<ChartData[]>

我正在尝试将其减少到ChartData[]. 我已经能够在subscribe操作员中做到这一点,并且图表显示了预期的数据,但我认为我应该能够作为一个可管道操作员来做到这一点?这是作为订阅的一部分完成的减少:

this.foodService.getAllReceipes()
  .subscribe((data) => {
    const list = data.reduce((arr: ChartData[], v: Recipe) => {
      const author = this.createOrFindAuthor(arr, v);
      author.y += 1;

      return arr;
    }, new Array<ChartData>());

    this.chartData$ = of(list.sort((a, b) => b.y - a.y));
  });

我曾尝试subscribe在可管道中使用代码,reduce但我收到编译错误,指出该方法需要Recipe[]该值。但是,如果我使用数组,那么我只能从 Observable 中获取第一个元素(或者我只是获取 Observable 并且需要对此做些什么?)

这是可能的,还是我对可管道操作员应该如何在 Observable 上工作的思考过程是错误的?

以下是模型和 createOrFindAuthor 函数供参考:

export class Recipe {

    public Title: string;
    public Author: string;
    public Source: string;
    public Page: number;
    public Link?: string;
}

export class ChartData {
    name: string;
    y: number;
}

private createOrFindAuthor(array: ChartData[], recipe: Recipe): ChartData {
  const name = (recipe.Author.length > 0 ? recipe.Author : 'UNKNOWN');

  let found = array.find(i => i.name === name);

  if (!found) {
    const newData = new ChartData();
    newData.name = name;
    newData.y = 0;
    array.push(newData);

    found = newData;
  }

  return found;
}
4

3 回答 3

4

因此,Chau Tran 把我放在了正确的位置上。显然我需要switchMapObservable 到 a Recipe[]reduce然后操作员很乐意接受 aRecipe作为值。解决方法如下:

this.foodService.getAllReceipes()
  .pipe(
    switchMap(data => data as Recipe[]),            <<== ADDED THIS

    reduce((array: ChartData[], value: Recipe) => {
        const author = this.createOrFindAuthor(array, value);
        author.y += 1;

        return array;
      }, new Array<ChartData>()),

      switchMap(data => this.chartData$ = of(data.sort((a, b) => b.y - a.y)))
  )
  .subscribe();
于 2018-05-03T13:21:25.527 回答
2

之后reduce,尝试:

switchMap(data => {
    this.chartData$ = of(data.sort((a, b) => b.y - a.y));
    return this.chartData$;
})
.subscribe()
于 2018-05-03T13:02:01.793 回答
0

我创建了这个stackblitz 示例来演示reduce(). 该项目包含其他内容,但您需要的是demoReduce.ts

import { Observable, of } from 'rxjs'
import { reduce, tap } from 'rxjs/operators'

type Book = {
  title: string
  noPages: number
}

type Library = {
  totalPages: number
  books: Book[]
}

export const demoReduce = () => {
  const books$: Observable<Book> = of(
    { title: 'book 1', noPages: 10 },
    { title: 'book 2', noPages: 20 },
    { title: 'book 3', noPages: 30 },
  )

  return books$.pipe(
    // --- reduce a stream of "Book" into a "Library"
    reduce<Book, Library>((previous, book) => {
      // --- add book to "Library" and increment totalPages in "Library"
      return {
        totalPages: previous.totalPages + book.noPages,
        books: [
          ...previous.books,
          book
        ]
      }
    }, { totalPages: 0, books: [] }),
    tap(val => console.log(val))
  )
}

要执行 observable,请使用“Demo Reduce”按钮,然后查看控制台。

它将流Books转换为单个Library对象。

笔记:

  • 我不确定为什么 stackblitz 在reduce(). 我没有在 IntelliJ/WebStorm 中得到错误。我怀疑是一个stackblitz错误。

更新:

这是作为输入的相同函数Observable<Book[]>(未测试):

export const demoReduceWithArray = () => {
  const books$: Observable<Book[]> = of([
    { title: 'book 1', noPages: 10 },
    { title: 'book 2', noPages: 20 },
    { title: 'book 3', noPages: 30 }
  ])

  return books$.pipe(
    // --- reduce a stream of "Book[]" into a "Library"
    reduce<Book[], Library>((previous, books) => {
      // --- add each book to "Library" and increment totalPages in "Library"
      books.map(book => {
        previous = {
          totalPages: previous.totalPages + book.noPages,
          books: [
            ...previous.books,
            book
          ]
        }
      })
      return previous
    }, { totalPages: 0, books: [] }),
    tap(val => console.log(val))
  )
}
于 2018-05-03T15:48:25.670 回答