Search code examples
angularserviceresolver

How to pass fetched data to a service?


I have created service ServiceA and ComponentA. ServiceA needs to be subscribed to queryParams of ActivatedRoute but I want to conditionally do it and the condition is a resolver data that is provided to ComponentA.

My solution is to check the condition in onInit of ComponentA and based on it subscribe ServiceA to queryParams. However, I initially wanted to subscribe to queryParams in the service's constructor and somehow inject data later. What do you think? Thanks.

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();
       }
     });
   }
}

Solution

  • I would suggest you to use rxjs and avoid doing subscribes.

    For example you can do something like this

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