是否可以将 BehaviorSubject 转换为数组流?

Is possible to cast BehaviorSubject into an array stream?

是否可以将 BehaviorSubject 转换或转换为数组流?或者请建议最佳做法。

Objective是到return杂货总价###

data.js

export const ShoppingList = {
  id: 22,
  username: 'Duff',
  groceries: [
    {
      day: 'Monday',
      purchases: [ { item: 'Beer', price: 10 }, { item: 'Pizza', price: 15 } ]
    },
    {
      day: 'Tuesday',
      purchases: [ { item: 'Wine', price: 10 }, { item: 'Steak', price: 15 } ]
    },
  ]
}

service.ts

import { Injectable } from '@angular/core';
import { ShoppingList } from './data.js'
//
import { BehaviorSubject } from 'rxjs';
import { pluck } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class DataService {
  shopping_list$ = new BehaviorSubject<any>(ShoppingList);

  user_name$ = this.shopping_list$.pipe(pluck('username');
  id$ = this.shopping_list$.pipe(pluck('id')

  **day$ = new BehaviorSubject<[]>(ShoppingList_groceries[0].day);**

  **purchases$ = new BehaviorSubject<[]>(ShoppingList_groceries[0].purchases);**

  constructor() {}
}

#

列表-component.ts

import { DataService } from '../service/data.service.ts';
//
import { from, Observable } from 'rxjs';
import { tap, map, pluck, reduce, switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css']
})

export class ListComponent implements OnInit {

  shopping_list = this.dataService.shopping_list$;
  user_name = this.dataService.user_name$;
  id = this.dataService.id$;
  day = this.dataService.day$

  ***prices = this.dataService.purchases$.pipe(
       pluck('prices'),
       reduce((a:number, c:number) => a + c),
       tap(y => console.log(y))
     );***


  constructor(private dataService: DataService) {}



  ngOnInit() {
    this.shopping_list.subscribe(val => console.log(val))
    this.prices.subscribe(val => console.log(val))
  }

}

> return未定义

> 或不采摘和减少 return 整个数组 [{},{}]

列表-component.html

<h1>{{ user_name }} {{ id }} </h1>
<p>{{ day }}</p>
<p>{{ prices }}</p>

是否可以通过管道让 BehaviorSubject*from 函数一样工作?这是最佳实践还是有更好的模式可以构建? 任何反馈将不胜感激。

行为主题

A Subject that requires an initial value and emits its current value to new subscribers

也就是说。把它想象成一个商店而不是一个数据流。你把东西放进去,一旦有人现在或以后订阅它,就会取回那个价值。

无法转换为数组流。

一种可能的方法如下:

首先按天收集和汇总所有购买。

  purchasesByDays$ = new BehaviorSubject<number[]>(
    ShoppingList.groceries.map(day => {
      return day.purchases.reduce((total, purc) => total + purc.price, 0);
    })
  );

完成后,在组件中使用一个简单的映射管道。

this.grandTotal$ = this.dataService.purchasesByDays$
  .pipe(
    map(
      (arr: number[]) => { 
        return arr.reduce((total: number, curr: number) => total + curr, 0);
    })
  );

演示 Stackblitz.