2016-11-29 134 views
6

我正在使用ngrx构建ng2应用程序。当应用程序启动时,会调用Web服务来获取初始数据,一旦获取了此数据,我会创建一个INIT_DONE操作。在使用URL参数加载页面之前等待ngrx动作

我的状态如下:

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

当我去的网页/我的空间/ 456,其中456是一个URL参数,我需要一些获取数据的,所以我得到的URL参数一样此:

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

SELECT_ACTION发现在所取得的数据的元件,并设置selectedDocument。问题是在INIT_DONE之前创建了SELECT_ACTION,并且在那一点documents为空。

如何在加载我的页面之前等待INIT_DONE

回答

6

我会利用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); 
} 

还将订阅分配给一个变量,以便在组件销毁时取消订阅。否则,您的订阅将在组件销毁后发生,并且您的行为仍有可能发生:

ngOnDestroy() { 
    this.subscription.unsubscribe(); 
} 
+0

有一个在_filter_ iteratee一个错字:_documents_ VS _document_。 –

+0

@JakubBarczyk谢谢! – chrigu

0

您可以选择从存储文档和订阅它,并从那里发出你的行动:

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

您需要一个解析器。解析器在完成导航操作之前等待数据可用。

@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')); 
    } 
} 

路由配置:

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

更多关于路由器的决心here

+0

解析器的问题在于UI将不会显示数据已加载......我们无法显示某些进度 – Sreekumar

相关问题