我在我的Angular项目中使用NgRx。我想从我的ProductsComponent
访问存储在我的商店中的产品。
ProductsComponent.ts
...
import { select, Store } from '@ngrx/store';
...
constructor(private store: Store<any>) {}
我想知道这两者的区别是什么:
public products = this.store.select(selectProducts);
和
public products = this.store.pipe(select(selectProducts));
和我应该用哪一个
两个选择方法的行为相同,具有相同的功能。不同之处在于,一个是存储上的方法,而另一个是RxJS管道。
NgRx团队提倡使用store.select
,因为它使用起来更友好(你不需要导入操作符)。甚至有一个eslint规则选择样式鼓励使用store.select
。
新的首选语法是
public products = this.store.pipe(select(selectProducts));
语法this.store.select
已弃用:
/**
* @deprecated Selectors with props are deprecated, for more info see {@link https://github.com/ngrx/platform/issues/2980 Github Issue}
*/
select<K, Props = any>(
mapFn: (state: T, props: Props) => K,
props: Props
): Observable<K>;
查看源代码:https://github.com/ngrx/platform/blob/master/modules/store/src/store.ts#L27-L33
自从Rxjs从链式API转变为可组合API(使用管道并导入你需要的操作符),他们就改变了这一点。这允许在Rxjs和Ngrx上摇树,现在推荐新的模式。