以下是一个使用Angular和NgRx实现条件选择和分发的示例:
import { Store } from '@ngrx/store';
import { AppState } from './app.state';
import { first } from 'rxjs/operators';
constructor(private store: Store) { }
selectAndDispatchAction(condition: boolean) {
this.store.select(state => state.someProperty)
.pipe(first())
.subscribe((value) => {
if (condition) {
this.store.dispatch({ type: 'ACTION_1', payload: value });
} else {
this.store.dispatch({ type: 'ACTION_2', payload: value });
}
});
}
this.selectAndDispatchAction(true);
或者
this.selectAndDispatchAction(false);
通过以上步骤,我们可以根据条件选择不同的action并将其分发到store中。在该示例中,我们使用NgRx的select
方法选择AppState
中的someProperty
属性,并根据条件选择不同的action来分发到store中。