0

我有一个名为 TransactionEntityService 的服务,它从 EntityCollectionServiceBase 派生,用于一个名为 Transaction 的模型。

export class TransactionEntityService
extends EntityCollectionServiceBase<Transaction> {

我正在使用 TransactionDataService 来覆盖 DefaultDataService 的默认行为。在 AppModule TransactionDataService 中是这样注册的

    export class AppModule {
  constructor(
    private eds: EntityDefinitionService,
    private entityDataService: EntityDataService,
    private transactionsDataService: TransactionsDataService
  ) {
    eds.registerMetadataMap(entityMetadata);

    entityDataService.registerService('Transaction', transactionsDataService);
  }
}

和 TransactionsDataService 覆盖 getAll 如下所示。

    export class TransactionsDataService extends DefaultDataService<Transaction> {
  constructor(
    http: HttpClient,
    httpUrlGenerator: HttpUrlGenerator,
    private notifyService: NotificationService
  ) {
    super('Transaction', http, httpUrlGenerator);
  }
  getAll(): Observable<Transaction[]> {
    return this.http
      .get<ApiResponse>('https://localhost:xxxx/transaction/GetLastSixMonth')
      .pipe(
        tap((data) => {
          this.notifyService.showSuccess(data.message, 'Sucess');
        }),
        map((res) => res.result),
        catchError((err) => {
          this.notifyService.showError(
            'Error While Six Month Transactions',
            'Error'
          );
          return of();
        })
      );
  }

实体服务的“$entitie”属性在调用 api 后返回正确的结果。我正在过滤该结果以计算名为 last6MonthDepositCount$ 的 observable 中的某些内容。

  this.last6MonthDepositCount$ = this.transactionsEntityService.entities$.pipe(
  map((transactions) => {
    const res = transactions.filter(
      (transaction) =>
        transaction.transactionType === TransactionType.Deposit
    ).length;
    return res;
  })//,
 // tap((val) => this.depositCount = val)
);

在 html 中我可以使用这个 observable

{{ last6MonthDepositCount$  | async }}

有用。

我应该怎么做才能在我的代码中的另一个变量中使用这个 observable 的值?

this.last6MonthDepositCount$.subscribe(x => this.dipositCount = x);

这种代码不起作用。我在 dipositCount 中得到 0,它看起来像 observable 的初始值。

在此处输入图像描述

4

1 回答 1

0

在这里,反应式范式命令式范式发生冲突。

myChart.data.datasets[0].datathis.last6MonthDepositCount$.subscribe(x => this.dipositCount = x);在给出最终值之前被调用。

您需要做的是: - 使用初始/默认值初始化chartJs,并在方法中ngAfterViewInit更新。myChartDatathis.last6MonthDepositCount$.subscribe()

如果您想从 2 个 observables 中获取结果,请使用combineLatest

const timerObservable1 = timer(0, 1000); 
    const timerObservable2 = timer(500, 1000); 
    const combinedTimers = combineLatest(timerObservable1, timerObservable2);
    combinedTimers.subscribe((value1, value2) => //DO something with both values together to update Chart);
于 2020-07-28T02:47:16.770 回答