Angular - NgRx - .select(...) 和 .pipe(select...) 之间的区别

Nic*_*ert 6 observable rxjs ngrx angular ngrx-store

我在我的 Angular 项目中使用 NgRx。我想从我的 访问存储在我的商店中的产品ProductsComponent

ProductsComponent.ts

...
import { select, Store } from '@ngrx/store';
...
constructor(private store: Store<any>) {}
Run Code Online (Sandbox Code Playgroud)

我想知道以下之间有什么区别:

public products = this.store.select(selectProducts);
Run Code Online (Sandbox Code Playgroud)

public products = this.store.pipe(select(selectProducts));
Run Code Online (Sandbox Code Playgroud)

以及我应该使用哪一个。

tim*_*ver 8

两种选择方法的行为相同并且具有相同的功能。区别在于,一个是 store 上的方法,而另一个是 RxJS 管道。

NgRx团队提倡使用,store.select因为它使用起来更加友好(不必导入算子)。甚至还有一个 eslint 规则选择风格鼓励使用store.select.


max*_*992 0

新的首选语法是

public products = this.store.pipe(select(selectProducts));
Run Code Online (Sandbox Code Playgroud)

该语法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>;
Run Code Online (Sandbox Code Playgroud)

请参阅此处的源代码: https: //github.com/ngrx/platform/blob/master/modules/store/src/store.ts#L27-L33

自从 Rxjs 从链式 API 转向可组合 API(使用管道并导入所需的运算符)以来,他们已经改变了这一点。这使得 Rxjs 上的 tree shake 成为可能,Ngrx 现在推荐新模式。

  • 只有以 props 作为参数的重载已被弃用,其余选项都很好。 (3认同)