我正在使用ngrx构建ng2应用程序.启动应用程序时,会调用Web服务来获取初始数据,一旦获取此数据,我就会创建一个INIT_DONE操作.
我的州看起来像这样:
export interface State {
documents: Document[];
selectedDocument: Document
}
Run Code Online (Sandbox Code Playgroud)
当我转到页面/ mypage/456,其中456是一个url参数时,我需要获取一些获取的数据,所以我得到这样的URL参数:
ngOnInit() {
this.paramSubscription = this.route.params
.select<string>('id')
.map((id) => new SelectAction(id))
.subscribe(this.store);
}
Run Code Online (Sandbox Code Playgroud)
所述SELECT_ACTION发现在所取得的数据,并设置在元件selectedDocument.问题是SELECT_ACTION是在INIT_DONE之前创建的,并且此时documents为空.
如何在加载页面之前等待INIT_DONE?
我会使用combineLatest运算符,因为它结合了多个源流的最新值.另外我会仔细检查是否使用过滤器设置了文档(这里我假设它是一个数组).
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);
}
Run Code Online (Sandbox Code Playgroud)
同时将订阅分配给变量,以便您可以在销毁组件时取消订阅.否则,您的订阅将在组件被销毁后出现,并且您的操作可能仍会被释放:
ngOnDestroy() {
this.subscription.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3629 次 |
| 最近记录: |