Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angular - Waiting for ngrx action before loading page with URL parameter

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
}

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

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.

How do I wait for INIT_DONE before loading my page ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...