1

I use Nx to create a new application using NgRx and DataPersistence.

I have generated several states in my application (example: State A, State B).

To retrieve the data via an API request to populate State A, I use in the effect associated with this.dataPersistence.fetch.

However to launch my API request, I need data contained in State B. This is where I block.

I saw that by using the basic effects, we can use the "withLastestFrom" operator to retrieve a different state than the one currently used.

@Injectable()
export class ElementEffects {
constructor (private store: Store<any>, private apiService: ApiService) {}

      @Effect()
      public yourEffect: Observable<Action> = this.actions$.pipe(
        ofType<yourActionClass>(ActionsEnum.YOUR_ACTION),
        withLatestFrom(this.store.pipe(select(selectSomethingFromTheStore))),
        concatMap(([action, selectedDateFromTheStore]) => this.apiService.doBackendCall(selectedDateFromTheStore, action.payload).pipe(
          map(([resultFromTheBackendCall, selectedDateFromTheStore]) => {
            // Do Stuff
          },
          catchError((error) => of(new FailureAction(error)))
          )
        ),
      );
}

However I do not know how to handle that with this.dataPersistence.fetch.

By opening the DataPersistent code (https://github.com/nrwl/nx/blob/master/packages/angular/src/runtime/nx/data-persistence.ts), I see that the fetch feature is already using the withLatestFrom operator. I do not see how to recover another State.

  fetch<A extends Action = Action>(
    actionType: string,
    opts: FetchOpts<T, A>
  ): Observable<any> {
    return this.actions.pipe(
      ofType<A>(actionType),
      withLatestFrom(this.store),
      fetch(opts)
    );
  }

My question is therefore: How to recover State B when I use a State A effect?

Hoping to be clear enough :)

4

2 回答 2

0

这是一个例子data-persistence.d.ts

@Injectable()
class TodoEffects {
  @Effect() loadTodo = this.s.navigation(TodoComponent, {
    run: (a, state) => {
      console.log(state); // Here you should see all the states in your app
      return this.backend.fetchTodo(a.params['id']).map(todo => ({
        type: 'TODO_LOADED',
        payload: todo
      }));
    },
    onError: (a, e: any) => {
      // we can log and error here and return null
      // we can also navigate back
      return null;
    }
  });
  constructor(private s: DataPersistence<TodosState>, private backend: Backend) {}
}
于 2019-09-11T16:47:26.583 回答
0

Yesfetch将返回整个状态存储。

因此,您需要选择要使用的商店的哪个部分(切片):

const state1 = state['state1'];
const state2 = state['state2'];

作为withLatestFrom拉动商店的“最新”状态。

于 2020-06-12T09:22:11.097 回答