Search code examples
angularobservablengrx

How to only subscribe to an observable after its data was fetched in Angular/NgRx?


I have a component where I wish to fetch some data from the backend when a button has been clicked, and based on that data navigate to the correct page.

I have the following code in the ngOnInit() function:

ngOnInit() {
  this.store.select(getUsers)
  .pipe()
  .subscribe((users) => {
    this.navigateToNextStep(users.length > 0);  // navigates to correct page based on the boolean parameter
  });
}

And I have the following function:

nextClicked() {
  this.store.dispatch(MyActions.getUsers());
}

The idea is that I would subscribe to the observable user list when creating the component, and then fetch the list when the button was clicked, triggering the subscription. However, the subscription gets triggered as soon as I enter the page, even though the user list was not fetched.

What is the correct way to achieve my goal where the navigation would only happen when the user list was actively fetched by the click? Also notice that the user list gets saved in the store, so I need to avoid any unintended behaviour in the case where the user returns to the page after navigating away.


Solution

  • you can use .pipe(filter(data => !!data)) to skip the initial empty value from the store