在@ngrx/store 中映射与订阅

map vs subscribe in @ngrx/store

我是angular2的新手,目前,我正在做一个使用@ngrx/store并订阅类的项目。我对 map 方法在订阅商店工作时不起作用感到困惑。请帮助我了解何时使用地图和订阅方法。代码如下。

this.store.select('rating').subscribe(({ topPicks }) => { // code is working });
this.store.select('rating').map(({ topPicks }) => // not working);

据我了解,这里 this.store.select('rating') 是一个 Observable。取决于 observable 是 Hot 还是 Cold,(有关更多信息,请阅读此 blog)observable 将开始发射值。在您的情况下,第一条语句有效,因为您正在订阅可观察的。 Map 只是一个运算符,您可以在可观察对象发出的值上使用它(它不能用作订阅者)。

第二条语句不起作用,因为没有 Observable 的订阅者。要使用地图运算符,您可以按如下方式操作:

this.store.select('rating').map(/* Do whatever you want to with the emitted values here */).subscribe(({ topPicks }) => {});

要了解更多有关运算符的信息,您可以查看 documentation