等待在异步路线守卫中填充NGRX状态



我的路线守卫需要等待状态填充,但是我只能获得第一个值,当然是null

export class Guard implements CanActivate {
  constructor(
    private router: Router,
    private store: Store<AppState>,
  ) {}
  canActivate(): Observable<boolean> {
    return this.store.select<MyState>('mystate').map(state => {
      if (state && state.thing) {
        this.router.navigate(['/path']);
        return true;
      }
    });
  }
}

我如何强迫警卫等待国家的人口居民?


[更新1]

如果我使用.skipWhile()模式:

return this.store
           .select<MyState>('mystate')
           .skipWhile(mystate => {
             if (mystate && mystate.thing) {
               return false;
             }
             console.log('here');
             return true; // <- shouldn't this cause it to keep going?
           })
           .do(mystate => {
             if (mystate.thing.condition) {
               this.router.navigate(['/path']);
             }
           })
           .mapTo(true);

.do(...)从未评估过,'here'仅记录一次。我想念什么?


[更新2]

缺少的是呼吁.dispatch()首先加载我的状态。我有一个嵌套的模块结构,并且将该防护设备放置在容器组件上是.dispatch()居住的位置。当然,警卫阻止了组件初始化,因此我的状态从未被填充。

您可以使用跳过操作员跳过null值。这样,只有在状态填充状态时,流才会发出。

return this.store.select<MyState>('mystate')
  .skipWhile(state => !state || !state.thing)
  // at this point, you're guaranteed that `state` is populated
  .do(() => this.router.navigate(['/path']))
  .mapTo(true);

这是一个JSBIN:http://jsbin.com/lupicepoyo/1/edit?js,,康斯

最新更新