【问题标题】:How to pass fetched data to a service?如何将获取的数据传递给服务?
【发布时间】:2020-04-05 19:38:31
【问题描述】:

我创建了服务ServiceAComponentAServiceA 需要订阅ActivatedRoutequeryParams,但我想有条件地订阅,条件是提供给ComponentA 的解析器数据。

我的解决方案是检查ComponentAonInit 中的条件,并根据它订阅ServiceAqueryParams。但是,我最初想在服务的构造函数中订阅queryParams,然后以某种方式注入数据。你怎么看?谢谢。

class ServiceA {
  constructor (private _route: ActivatedRoute) {}

  subscribeToQueryParams() {
     this._route.queryParams
     .subscribe(params => {
         ...
     });
  }
}

class ComponentA implements OnInit {
   constructor (private serviceA: ServiceA, private _route: ActivatedRoute) {}

   ngOnInit() {
     this._route.data.subscribe(condition => {
       if(condition) { 
         this.serviceA.subscribeToQueryParams();
       }
     });
   }
}

【问题讨论】:

    标签: angular service resolver


    【解决方案1】:

    我建议你使用 rxjs 并避免订阅。

    例如你可以做这样的事情

    class ComponentA implements OnInit {
      constructor (private serviceA: ServiceA, private _route: ActivatedRoute) {}
    
      ngOnInit() {
       this._route.data.pipe(
         switchMap(condition => {
            if(condition) { 
              this.serviceA.subscribeToQueryParams();
            }
        })
       );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-03-06
      • 2021-10-27
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      相关资源
      最近更新 更多