状态管理 - 使用选择器读取应用程序状态

优质
小牛编辑
115浏览
2023-12-01

For example, here’s how you would select the object:

And to fetch the counter’s currentValue, we can pass in a string array, where each string plucks a single property from the application state one at a time in the order specified:

Because of that, allows you to select values using functions too, which makes things more type-safe and your selectors will be more refactorable by your IDE.

While you could inject Store and select values directly in your Angular components, it’s considered to be a best practice to wrap this functionality into separate services. This approach encapsulates all of the selection logic and eliminates any duplication where the selection path is repeated throughout your application.

app/services/counter.service.ts

Because select() returns an , the getCurrentValue() method also applies a filter() to ensure that subscribers do not receive any falsy values. This greatly simplifies the code and templates in your components, since they don’t have to repeatedly consider the falsy case everywhere the value is used.