【问题标题】:issue with using facade method in NGRX in Angular在 Angular 的 NGRX 中使用外观方法的问题
【发布时间】:2022-06-14 22:33:53
【问题描述】:

我正在使用 NGRX 和外观。我面临一些问题。当我打电话时getLedgerAccountTypes()的方法正面它使api请求t 并回馈回复.但问题是我不能使用.pipe().subscribe()有了它,我无法将数据分配给组件中的变量。另一方面,我有getLedgerAccountTypes$()我可以用它.pipe().subscribe()但它不会发出 api 请求并从状态中选择。我需要一种可以发出 api 请求、获得响应并且可以将数据分配给组件中的变量的方法。我附上了我的代码。请查看我的代码,让我知道如何修复它。

ngOnInit(): void {
    this.facade.getLedgerAccountTypes();
    this.facade
      .getLedgerAccountTypes$()
      .pipe(takeWhile(() => this.alive))
      .subscribe((response: LedgerAccountTypeDef) => (this.ledgerAccountTypes = response.data));
  }

import { Injectable } from \'@angular/core\';

import { Observable } from \'rxjs\';

import { Store } from \'@ngrx/store\';

import { FieldUsageType } from \'../../../../shared/enums/field-usage-type\';
import {
  LedgerAccountTypeDef
} from \'../../../../shared/model/cashbook-def.interface\';
import * as fromActions from \'./add-new-ledger-account.actions\';
import * as fromSelectors from \'./add-new-ledger-account.selectors\';
import { AddNewLedgerAccountState } from \'./add-new-ledger-account.state\';

@Injectable({
  providedIn: \'root\'
})
export class AddNewLedgerAccountFacade {
  constructor(private store$: Store<AddNewLedgerAccountState>) {}

  getLedgerAccountTypes(): void {
    this.store$.dispatch(new fromActions.GetLedgerAccountTypesRequest());
  }

  getLedgerAccountTypes$(): Observable<LedgerAccountTypeDef> {
    return this.store$.select(fromSelectors.ledgerAccountTypesSelector);
  }
}

    标签: angular ngrx ngrx-store facade


    【解决方案1】:

    使用RxJs of 尝试以下代码,您将在使用switchMap 从商店调用选择之后立即将您的第一个调用包装在Observable 中,最后使用您的逻辑订阅。

    of(this.facade.getLedgerAccountTypes())
           .pipe(
             switchMap(() => this.facade.getLedgerAccountTypes$()),
             takeWhile(() => this.alive)
           )
    .subscribe((response: LedgerAccountTypeDef) => (this.ledgerAccountTypes = response.data));
    

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 2012-05-02
      相关资源
      最近更新 更多