如何使用DataPersistence同时使用2个状态

时间:2019-06-25 10:35:37

标签: nrwl nrwl-nx

我使用Nx使用NgRx和DataPersistence创建一个新的应用程序。

我在应用程序中生成了多个状态(例如:状态A,状态B)。

要通过API请求检索数据以填充状态A,我使用了与this.dataPersistence.fetch关联的效果。

无论如何启动我的API请求,我都需要状态B中包含的数据。 这是我阻止的地方。

我看到通过使用基本效果,我们可以使用“ withLastestFrom”运算符来检索与当前使用的状态不同的状态。

@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)))
          )
        ),
      );
}

但是我不知道如何使用this.dataPersistence.fetch处理它。

通过打开DataPersistent代码(https://github.com/nrwl/nx/blob/master/packages/angular/src/runtime/nx/data-persistence.ts),我看到fetch功能已经在使用withLatestFrom运算符。我看不到如何恢复另一个国家。

  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)
    );
  }

因此,我的问题是: 使用状态A效果时如何恢复状态B?

希望很清楚:)

2 个答案:

答案 0 :(得分: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) {}
}

答案 1 :(得分:0)

是的fetch将返回整个状态存储。

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

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

withLatestFrom拉出商店的“最新”状态。