简体   繁体   English

Angular 8 Ngrx存储如何在没有订阅回调的情况下获取reducer的值?

[英]Angular 8 ngrx store how to get reducer value without subscribe callback?

I am new to the angular and rx. 我是angular和rx的新手。

I see a lot of examples just use code something like this. 我看到很多示例只是使用类似这样的代码。

this.store.select('city')
this.store.pipe(select(action()))

However, those code just returning _Store instance. 但是,这些代码只是返回_Store实例。

The correct way to get value from reducer is that 从减速器获得价值的正确方法是

this.store.pipe(select(action())).subscribe(val => this.val)

Is there any way I can just get value from reducer without callback or subscribe? 有什么方法可以让我从reducer获得价值而无需回调或订阅?

Something like generator in redux saga ?? 像redux saga中的generator一样?

const city = yield select(state => state.city) 

If you just need a value in a html template, I suggest not subscribing, but referencing this observable directly in the template together with an async pipe. 如果您只需要html模板中的值,则建议不要订阅,而是直接在模板中引用可观察到的值以​​及async管道。

//typescript
public value$ = this.store.pipe(select(...));
//html
{{ value$ | async` }}

If you need a value of the stream in the TS code and you want to unsubscribe from the observable just after accessing the value (you dont want to call callback whenever new value is emmited), you can use operator take(1) : 如果您需要TS代码中的流的值,并且想要在访问该值后立即取消对可观察对象的订阅(您不希望在发出新值时调用回调),则可以使用运算符take(1)

this.store.pipe(select(...)).pipe(take(1)).subscribe(...)

I use a wrapper (that I wrote) around ngrx/store, and it allows such an operation using code like this: 我在ngrx / store周围使用了一个包装程序(我写过),它允许使用如下代码进行此类操作:

store('city').state(); // returns the current value of `city`

Or, equivalently (and more recommended according to its style guide): 或者,等效地(并根据其样式指南进一步推荐):

store.state().city;

The wrapper is ng-app-state . 包装器是ng-app-state It is a shift in thinking from the traditional action/reducer patterns of ngrx, but one that has worked well for me. 与传统的ngrx行动/减少器模式相比,这是一种思维上的转变,但对我来说效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM