NGRX选择器在商店中可用之前请求数据

问题描述 投票:4回答:5

当用户选择屏幕上的项目时,触发动作,该动作从api请求数据并将该数据加载到所选项目的商店中。

选择器用于获取返回数据的特定部分以创建图形。

选择器返回undefined,因为商店还没有该数据。

我要么需要store / action / dispatch来向选择器发出信号,告知它已准备就绪或允许选择器继续请求,直到它有它正在寻找的数据为止:

this.setItemDispatch(this.datetime, this.selectedItem, this.direction);

this.store.select(selectFlyoutTimelineBar(this.selectedItem, this.direction, 'Graph Title')).subscribe(x => {
  console.log('data returned:', x);
});

发货:

this.store.dispatch(
          new LoadStationArriveTimelineDataAction({
            station: selectedItem,
            start: { startDate: currentDate },
            query: this.codes,
            lineQuery: this.lineCode
          })
        );
angular rxjs ngrx rxjs6
5个回答
2
投票

类似于@timdeschryver所说的“,一个选择器是一个RxJS可观察的,每当它的数据发生变化时,它就会发出一个新的值。这意味着你不需要通知选择器进行更新。”我的选择器没有拿起商店的更新,因为没有任何东西告诉我的选择器商店更新了。我的选择器过滤商店数据,而不是观察商店中商品的直接更改。

我有另一个选择器正在寻找特定项目的更改。我订阅了那个选择器并将我的selectFlyoutTimelineBar选择器嵌套在那里,基本上说,“当你选择的项目被更新时,抓住图形数据,因为它现在可用”


1
投票

您可以使用RxJS filter操作。

this.store.pipe(
  select(selectFlyoutTimelineBar(this.selectedItem, this.direction, 'Graph Title')),
  filter(result => Boolean(result))
)

我要么需要store / action / dispatch来向选择器发出信号,告知它已准备就绪或允许选择器继续请求,直到它有它正在寻找的数据为止:

选择器是一个RxJS可观察对象,每次更改数据时它都会发出一个新值。这意味着您不需要通知选择器进行更新。


0
投票

看起来你正在寻找combineLatest运算符,当所有源Observable发出至少一个项目然后从任何源Observable发出时,它会发出。但是很难说出你想要做什么:

const selector$ = action$.pipe(ofType(...))

combineLatest(this.store.select(...), selector$)
  .pipe(
    map([data, selector] => /* filter data or whatever */)
  )
  .subscribe(...)

也许你甚至不需要使用map()

如果选择器是另一个Observable,并且在制作this.store.select(...)请求之前需要它的值,你可以用concatMap链接它,例如:

selector$
  .pipe(
    concatMap(selector => this.store.select(...selector...))
  )
  .subscribe(...)

0
投票

如果数据不可用,则选择器返回null。然后在您的子中,您可以按如下方式过滤null:

this.store.select(selectFlyoutTimelineBar(this.selectedItem, this.direction, 'Graph Title'))
  .pipe(
    filter(x => x != null)
  )
  .subscribe(x => {
    console.log('data returned:', x);
  });

这将导致sub仅在选择器不返回null时执行。 PS你的select语句应该在pipe()里面


0
投票

看来你需要定义一个initialState并使它成为你的reducer的默认值。

export const initialState: State = { prop1: null, prop2: null }

然后在你的减速机

export class reducer(state: State = initialState, action: YourAction)

它将确保消除undefined并在价值可用之前很好地处理商店。

© www.soinside.com 2019 - 2024. All rights reserved.