等待ngrx操作,然后再加载带有URL参数的页面 [英] Waiting for ngrx action before loading page with URL parameter

查看:76
本文介绍了等待ngrx操作,然后再加载带有URL参数的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ngrx构建ng2应用程序.启动应用程序后,将调用一个Web服务来获取初始数据,一旦获取了这些数据,我就会创建一个 INIT_DONE 操作.

I'm building an ng2 application using ngrx. When the app is launched a web service is called to get initial data, once this data is fetched I create an INIT_DONE action.

我的状态看起来像这样:

My State looks like this :

export interface State {
  documents: Document[];
  selectedDocument: Document
}

当我进入页面/mypage/456时,其中456是一个url参数,我需要获取一些获取的数据,以便获得这样的URL参数:

When I go to the page /mypage/456 where 456 is a url parameter, I need to get some of the fetched data so I get the URL parameter like this :

ngOnInit() {
  this.paramSubscription = this.route.params
    .select<string>('id')
    .map((id) => new SelectAction(id))
    .subscribe(this.store);
}

SELECT_ACTION 在获取的数据中查找元素并设置selectedDocument.问题是 SELECT_ACTION 是在 INIT_DONE 之前创建的,而此时documents为空.

The SELECT_ACTION finds the element in the fetched data and sets selectedDocument. The problem is that the SELECT_ACTION is created before INIT_DONE and at that point documents is empty.

在加载页面之前,如何等待 INIT_DONE ?

How do I wait for INIT_DONE before loading my page ?

推荐答案

我会使用 combineLatest 运算符,因为它结合了多个源流的最新值.另外,我还要使用过滤器仔细检查文档是否已设置(这里假设是数组).

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

这篇关于等待ngrx操作,然后再加载带有URL参数的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆