简体   繁体   中英

What is the correct way to call an NgRx loading spinner

I have a loading-spinner component where I can show and hide by dispatching NgRx actions like:

this.store.dispatch(loadingActions.loadingShow());

this.store.dispatch(loadingActions.loadingHide());

Now I can use them in NgRx effects just fine when making API calls. However I would also like to be able to use them in my components where I am listening to store changes using select(). An example scenario is when I need to delay the loadingHide() action until I have completed some processing of the API results in my component, for example:

this.dataSource$ = this.store.pipe(
      tap(data => {
        this.store.dispatch(loadingActions.loadingShow());   //this line will cause an infinite loop
      }),
      select(RecordSelectors.selectActiveItems),
      tap(data => {
        //DO SOME PROCESSING HERE

        //hide the loading spinner
        this.store.dispatch(loadingActions.loadingHide());
      })
    );

The issue above is when I dispatch the loadingShow action, I am causing the stream to stuck in an endless loop of emitting and listening. So I know the code above is broken but I am just trying to explain what I am going for. Is it even possible or am I doing things incorrectly?

What are you doing that you want to show a spinner here? And where's is slow, is it the selector that's slow, or the processing? If it's the latter, you can do:

this.dataSource$ = this.store.pipe(
      select(RecordSelectors.selectActiveItems),
      tap(data => {
        this.store.dispatch(loadingActions.loadingShow()); 

        //DO SOME PROCESSING HERE

        //hide the loading spinner
        this.store.dispatch(loadingActions.loadingHide());
      })
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM