08 Sep 2020
3 min

How I Got Rid of State Observables in Angular

When developing a complex SPA in Angular, using a state management library makes things so much easier.

The app store acts as a single source of truth and contains all the data that is fundamental to the correct functioning of the app.

Thanks to the store, I can access or edit this data from any smart component (or container).

However, it can be frustrating to deal with all the subscriptions to the store; many times I have to deal with multiple @Select() in a single component, each of which returns an Observable of its correspondent property in the app store.

And for each of these Observables, I need to create a subscription that will be destroyed at the end of the component lifecycle…that’s a lot of code!

But what if we could get rid of all the Observables?

In the simplest cases, we can avoid explicit subscriptions using the async pipe, which will subscribe to the Observable and read the last value emitted for us.

Suppose that we have a @Select() decorator like this__:__

@Select(ListState.SelectAllItems) listItems: Observable<string[]>;

We can use it immediately with the async pipe in our HTML:

<ul> 
  <li *ngFor="let item of listItems | async">{{item}}</li>
</ul>

On the other hand, many cases require us to subscribe to the Observables in our components so that we can use the values they emit in other methods.

(To learn about how to set up a store and see the above examples in a project, you can read my article How to Create a Simple Store in Angular.)


Introducing @ngxs-labs/select-snapshot

@ngxs-labs/select-snapshot is an experimental feature for NGXS developed by NGXS Labs.

Even though it’s still not part of the official NGXS package, it is likely to become an official feature shortly. The package allows us to replace the @Select() decorator with @SelectSnapshot().

But what’s the difference between them?

While the former returns an Observable we need to subscribe to, the latter subscribes to the store for us and returns the last value emitted! To see it in action, let’s install the package with the command:

npm install @ngxs-labs/select-snapshot

And then, let’s include it in our appModule:

@NgModule({
 declarations:
  [AppComponent,
   ListContainerComponent,
   ListItemInputComponent,
   ListComponent
  ],
  imports: 
   [BrowserModule,
   AppRoutingModule,
   FormsModule,
   ReactiveFormsModule,
   NgxsModule.forRoot([ListState]),
   NgxsReduxDevtoolsPluginModule.forRoot(),
   NgxsSelectSnapshotModule.forRoot()
   ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule {}

Now we can replace the @Select() decorator:

@Select(ListState.SelectAllItems) listItems:Observable<string[]>;
@SelectSnapshot(ListState.SelectAllItems) listItems: string[];

And use the value emitted from the store without subscribing!

<ul> 
 <li *ngFor="let item of listItems">{{item}}</li>
</ul>

The @ViewSelectSnapshot decorator

The  select-snapshot library  also exposes a second selector, @ViewSelectSnapshot(). Choosing between this and the simple @SelectSnapshot() can make a difference according to the change detection strategy of the component in which we are using the above decorators.

Let's suppose we have a presentational component with change detection set on OnPush :

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})

export class MyComponent {
  @SelectSnapshot(ListState.SelectAllItems) listItems: string[];
  @ViewSelectSnapshot(ListState.SelectFilteredItems) filteredItems: string[];
}

This means that the component will not be constantly checked for changes, but a check will be triggered by any user interaction.

In this situation,  @ViewSelectSnapshot , unlike his sibling @SelectSnapshot, will call the markForCheck() method on the component when the state gets updated, thus triggering the change detection.

For this reason, the NgXs team recommends to use @ViewSelectSnapshot instead of @SelectSnapshot for template binding and dynamic rendering.

In Conclusion

The select-snapshot library offers very powerful tools to avoid subscribing to Observables in our components. It makes life so much easier, but pay attention to the change detection!

Frequently asked questions

What is the difference between @Select() and @SelectSnapshot() in NGXS?

@Select() returns an Observable that you must subscribe to, while @SelectSnapshot() from @ngxs-labs/select-snapshot subscribes to the store for you and gives you the last value emitted as a plain property. That means you can read listItems directly in methods or templates without managing subscriptions or calling unsubscribe at the end of the component lifecycle.

How do I avoid subscribing to NGXS store Observables in Angular components?

The async pipe subscribes to an Observable in your template and reads the most recent value it emits, so you can bind listItems | async inside *ngFor without a manual subscription. This works for simple template bindings, but when you need the values inside component methods, a manual subscription is required. The @SelectSnapshot() decorator from @ngxs-labs/select-snapshot removes that need entirely by exposing the latest store value as a plain property.

When should I use @ViewSelectSnapshot() instead of @SelectSnapshot() with OnPush change detection?

Use @ViewSelectSnapshot() when a component uses ChangeDetectionStrategy.OnPush and the value drives template bindings. Unlike @SelectSnapshot(), it calls markForCheck() on the component when the state updates, which triggers change detection. Because an OnPush component is otherwise checked only on user interaction, a plain @SelectSnapshot() value may not refresh in the view. The NGXS team recommends @ViewSelectSnapshot() for template binding and dynamic rendering.

How do I install and set up @ngxs-labs/select-snapshot in an Angular app?

Install the package with npm install @ngxs-labs/select-snapshot, then import NgxsSelectSnapshotModule.forRoot() into your AppModule imports alongside NgxsModule.forRoot([ListState]). After that, replace @Select() with @SelectSnapshot() and pass the same state selector, such as ListState.SelectAllItems. You need an NGXS store already set up before this works.

Is @ngxs-labs/select-snapshot an official part of NGXS?

No, @ngxs-labs/select-snapshot is an experimental feature from NGXS Labs and is not yet part of the official NGXS package. The author expects it to become an official feature shortly, so until then it must be installed separately with npm. The @Select() decorator remains the official way to get Observables from the store.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.