this.store.select(state => state.name);

最近在做Angular的项目,遇到了一个问题,看不懂this.store.select();这个方发代表的是什么意思?

查了一些资料最后明白了一些。。。

In very simple terms select gives you back a slice of data from the application state wrapped into an Observable.

What it means is, select operator gets the chunk of data you need and then it converts it into an Observable object. So, what you get back is an Observable that wraps the required data. To consume the data you need to subscribe to it.

So, when we think of ngrx/store as a database and the selectors are like SELECT in SQL queries – they gives us back information we want. As our state tree grows deeper, it would become more complex to get state out of the store.
We may find ourselves writing complex data transformation logic in our components to get exactly what we need – however we don’t want to do that – and this is where selectors come into play. Just like with databases, we can perform data transformation from within the store by composing selectors to just return what we need. We’ll keep our components lean and decoupled from the Store.

 

大意是:

简单地说,select从应用程序状态返回一段数据,并将其包装成一个可观察的对象。

它的意思是,select运算符获取所需的数据块,然后将其转换为可观察对象。所以,你得到的是一个可以观察到的包所需数据。要使用需要订阅的数据。

因此,当我们将ngrx/store看作一个数据库时,选择器就像SQL查询中的SELECT一样——它们会返回我们想要的信息。随着我们的状态树越来越深,将状态从存储中取出会变得更加复杂。

我们可能会发现自己在组件中编写复杂的数据转换逻辑,以获得我们所需要的——但是我们不想这样做——而这正是选择器发挥作用的地方。就像使用数据库一样,我们可以通过组合选择器从存储区内执行数据转换,以返回我们需要的内容。我们将保持我们的组件精简,并与Store分离。

举个简单的例子:

1.先定义store的模型

export interface AppStore { clock: Date }

2.将Store导入你所在的组件对象:import { store } from '@ngrx/store'

3.然后在构造函数中通过注入(或者定义)的方式创建一个store: 

constructor(private store: Store<AppStore>){}

4.选择一个可返回的可观察对象

在你的组件中声明一个 clock 的变量:

public clock: Observable<Date>;

然后你就可以像下面这样用了:

this.clock = this.store.select('clock');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值