Ngrx 调度后选择数据
2021-11-08
2333
我有一个方法来分派操作以查询帐户并选择帐户。 我不确定这是否是分派后选择数据的最佳实践。
this._store.dispatch(AccountsPageActions.loadAccountWithDetails({ accountId: this._accountId }));
this.account$ = this._actionsSubject.pipe(
filter(action => action.type === AccountsApiActions.loadAccountWithDetailsSuccess.type),
switchMap(() => this._store.select(getAccountDetailById(this._accountId)).pipe(
tap(account => {
this.account = account;
this.accountId = this._accountId;
this._reportsService.setAccount(account);
})
))
);
有人可以告诉我更好的做法吗?或者这是可行的方法吗?
2个回答
您不需要监听动作调度。如果设计正确,您的动作将更新状态,选择器也将更新。这就足够了
ngOnInit() {
this._store.dispatch(AccountsPageActions.loadAccountWithDetails({ accountId: this._accountId }));
// If you want to use the account$ with async pipe
account$ = this._store.select(getAccountDetailById(this._accountId)).pipe(
filter(account => !!filter), // ignore if no account is returned
tap(account => {
this.account = account;
this.accountId = this._accountId;
this._reportsService.setAccount(account);
})
); // or .subscribe();
}
我会避免监听组件中的动作调度,而是使用效果来实现这一点。
mat.hudak
2021-11-08
我不知道您为什么需要动作主题,您可以使用下面的代码订阅动作,并且只要分派该动作就会触发。将动作订阅保留在您的构造函数中,然后您可以在组件中的任何位置分派您的动作
PLUCK 用于从 payload
import { Actions, ofType } from '@ngrx/effects';
import { map, pluck, switchMap, tap } from 'rxjs/operators';
...
constructor(private action: Actions) {
const sub = this.action.pipe(
ofType(AccountsApiActions.loadAccountWithDetailsSuccess.type),
pluck('accountId'),
switchMap((accountId) => this._store.select(getAccountDetailById(accountId)).pipe(
tap(account => {
this.account = account;
this.accountId = this._accountId;
this._reportsService.setAccount(account);
}))).subscribe();
}
ngOnInit() {
this._store.dispatch(AccountsPageActions.loadAccountWithDetails({ accountId: this._accountId }));
}
中获取 accountId 值
Fateh Mohamed
2021-11-08