繁体   English   中英

等待ngrx状态填充在异步路由防护中

[英]Wait for ngrx state to be populated in async route guard

我的路线防守需要等待状态被填充,但我只获得第一个值,当然, 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()所在的位置。 当然,警卫阻止组件初始化,因此我的状态从未填充过。

您可以使用skipWhile运算符跳过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,console

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM