简体   繁体   English

ngrx订阅服务还是从组件传递数据?

[英]ngrx subscribe in service or pass data from component?

I need advice, i need data from store in service (my service use Angulartics to send data to Google Analytics). 我需要建议,我需要服务中存储的数据(我的服务使用Angulartics将数据发送到Google Analytics(分析)。 I stored all needed data as object in store, what is better: 我将所有需要的数据作为对象存储在存储中,这更好:

  1. Subscribe to store in my service, which send data each time to analytics. 订阅以存储在我的服务中,该服务每次都将数据发送到分析。
  2. Inject store to each component, get data - send to service, then unsubscribe? 将存储注入每个组件,获取数据-发送给服务,然后退订?

Also, i dispatching action when getting information in service. 另外,在服务中获取信息时,我会调度操作。 How i can create store field listener ? 我如何创建商店字段侦听器? (get the data when this field will not be undefined) (在此字段未定义时获取数据)

To me this is a good time to use @ngrx/effects . 对我来说,这是使用@ ngrx / effects的好时机。 If you're already using @effects , then this shouldn't be too difficult to leverage. 如果您已经在使用@effects ,那么利用它应该不会太困难。 If not, a general pattern you might have to adopt is to move your Service call that loads the data (ie side effects like asynchronous service calls) to an effects file. 如果不是这样,您可能必须采用的一般模式是将将数据(即副作用,如异步服务调用)加载到效果文件的Service调用。 Then you can do something like this to track analytic events. 然后,您可以执行类似的操作来跟踪分析事件。 It has the benefits mentioned above of having it tracked in one place. 它具有在一个地方进行跟踪的上述好处。

@Effect({ dispatch: false })
trackEvents = this.actions.pipe(
  ofType(...),
  tap(({ type, payload }) => {
    // make call to Angulartics
    this.angulartics2.eventTrack.next({ 
      action: type, 
      properties: { ...payload },
    });
  })
)

The code snipped is copied from https://blog.angularindepth.com/start-using-ngrx-effects-for-this-e0b2bd9da165#8a65 . 截断的代码是从https://blog.angularindepth.com/start-using-ngrx-effects-for-this-e0b2bd9da165#8a65复制的。

The first approach make sense, it will keep the logic in one place. 第一种方法很有意义,它将逻辑放在一个地方。 What you need to do is to subscribe the store changes in your service and then send this to analytics service: 您需要做的是订阅服务中的商店更改,然后将其发送到分析服务:

You can inject the Store service into your services. 您可以将商店服务注入您的服务中。 Use store.select to select slice(s) of state: 使用store.select选择状态片:

and inside the constructor of the service you can subscribe to the changes in your object like this: 在服务的构造函数中,您可以订阅对象中的更改,如下所示:

this.store.select('keyName').subscribe( (data)=> {
 // do whatever you want with this data
});

I read this article https://brianflove.com/2017/11/01/ngrx-anti-patterns/ and managed not to subscribe explicitly in component or service and not to use any effects. 我阅读了https://brianflove.com/2017/11/01/ngrx-anti-patterns/的这篇文章,并设法不明确地订阅组件或服务,也不使用任何效果。 First step is making service method listening for filter change, passing data via pipe to http request, then dispatching event with this data and returning observable of results 第一步是使服务方法侦听过滤器更改,通过管道将数据传递到http请求,然后使用此数据调度事件并返回可观察到的结果

getCarItems(): Observable<ICarItem[]> {
 return  this.store.select(state => state.filter).pipe(
           map (source=> 
            {
            let productId=source.product ? source.product.productId:'';
            let brand = source.brand||'';            
            return({productId ,brand})                
            }),
        switchMap(value => this.http.get(`${this._baseUrl}api/caritems`,{params:value})),
        tap((list:ICarItem[]) => {        
          this.store.dispatch(new LoadCarItemsAction(list));}          
       ),
       switchMap(()=>this.store.select(state=>state.carItems))        
       )
}

Second step is to pass results to observable in component: 第二步是将结果传递给组件中的可观察对象:

ngOnInit() {   
   this.carItems$ = this.myService.getCarItems();
  }

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

相关问题 如何订阅从 ngrx 的实体数据服务返回的 Observable - how to subscribe to an Observable returned from ngrx's Entity Data Service 从服务获取数据到组件订阅方法 - get data from service to component subscribe method 如果 REDUX 中的值正在从其他组件更新,则从ngrx 选择器获取的ngrx 可观察数据不会在订阅之外更新 - ngrx observable data took from a ngrx selector is NOT getting updated outside subscribe if the value in REDUX is getting updated from other component Angular 2订阅组件或服务? - Angular 2 subscribe from component or service? 订阅一次 ngrx-data 服务调用被调用两次 - Subscribe geting called twice for a single ngrx-data service call Angular 2中的.subscribe通过服务将组件中的数据发布到服务器 - .subscribe in Angular 2 to post data from a component to server via a service ngrx如何在组件中订阅动作或订阅状态 - ngrx How to subscribe to action in component or subscribe to state NativeScript如何将数据从服务传递到组件? - NativeScript How to pass Data from service to component? 无法将数据从服务传递到Angular中的组件 - Unable to pass data from Service to a Component in Angular 无法将数据从组件传递到服务 - Unable to pass data to service from component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM