Waiting for ngrx action before loading page with URL parameter

旧巷老猫 提交于 2019-11-29 07:08:52

I would make use of the combineLatest operator as it combines the latest values of multiple source streams. In addition I'd double-check that documents is set (here I assumed it's an array) using filter.

ngOnInit() {
  this.subscription = Observable.combineLatest(
      this.store.select("documents")
          .filter(documents => documents.length > 0),
      this.paramSubscription = this.route.params
          .select<string>('id')
  )
  .map((combinedData: [Object[], string]) => combinedData[1])
  .subscribe(this.store);
}

Also assign the subscription to a variable so that you can unsubscribe when the component is destroyed. Otherwise your subscription will be around after the component has been destroyed and it's possible that your action still gets emitted:

ngOnDestroy() {
    this.subscription.unsubscribe();
}
André Werlang

You need a resolver. A resolver waits until data is available before completing the navigation action.

@Injectable()
export class DocumentsResolver implements Resolve {

    constructor(
        private store: Store
    ) {}

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Hero> {
        // take id from snapshot
        const id = route.params['id'];
        // start with the document list
        return this.store.select('documents')
          // wait until there is data available
          .filter(documents => documents && documents.length > 0)
          // then produce the selected document
          .mergeMapTo(this.store.select('selectedDocument'));
    }
}

On route configuration:

export const DocumentsRoutes: RouterConfig = [
    { path: 'documents/:id', component: DocumentsDetailComponent, resolve: { document: DocumentsResolver } }
];

More about router resolve here

You could select documents from the store and subscribe to it and emit your action from there:

ngOnInit() {
  this.store.select("documents").subscribe(documents => {
    this.paramSubscription = this.route.params
      .select<string>('id')
      .map((id) => new SelectAction(id))
      .subscribe(this.store);
  });  
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!