-1

I have a component that calls a service. The service makes a http call. On receiving a response I want to call a function in the component from the service. How can it be done?

This is my component

import { ExportService } from '../menu/export.service';
export class Component {

   constructor(public exportService: ExportService) {
   }

   functionToCallFromService(){
   }

   export(){
       this.exportService.export()
   }
}

Here is my Service, which makes an HTTP Post call. downloadFile() is just a function in the service that gets called once the response is received. Is there any way I can call the functionToCallFromService() of the component, once the response is received

Service is as follows

@Injectable()
export class ExportService {
 export() {
    this._http.post(urlToMakePostCall, formData, { responseType: 'blob' 
    }).retry(3)
     .subscribe(response => { this.downloadFile(response, 
     filename)},
     error => { throw new Error(error); });

}
PipoTells
  • 511
  • 6
  • 11
  • Possible duplicate of [How to call component method from service? (angular2)](https://stackoverflow.com/questions/40788458/how-to-call-component-method-from-service-angular2) – Krishna Mohan Feb 03 '18 at 11:15
  • Return an observable from the service? Have an explicit callback argument to `export`? – jonrsharpe Feb 03 '18 at 11:16
  • @Pipo Tells, the usual way is that the services only serve Observables, it's in the component where you subscribe to the observable and then you call the function – Eliseo Feb 03 '18 at 11:51

1 Answers1

0

You shouldn't call a component method from your service. Thats not a really good idea in general, as your service will end up being usable only by a single controller. What you should do, is returning a value from the service and handle that value from your controller (there is no need to return an Observable or a Promise, it can be literally anything)

import { ExportService } from '../menu/export.service';
export class Component {

   constructor(public exportService: ExportService) {
   }

   functionToCallFromService(){
   }

   export(){
       this.exportService.export().subscribe(value => console.log(value))
   }
}

@Injectable()
export class ExportService {
 export() {
    const responseType = 'blob';
    return this._http.post(urlToMakePostCall, formData, { responseType })
        .retry(3)
  }
}
nicowernli
  • 3,250
  • 22
  • 37