How to call back a function in Angular 4 Component from Service

时间:2018-02-03 11:11:53

标签: angular

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

}

1 个答案:

答案 0 :(得分:0)

您不应该从服务中调用组件方法。这一般不是一个好主意,因为您的服务最终只能由一个控制器使用。你应该做的是从服务返回一个值并从你的控制器处理该值(没有必要返回一个Observable或一个Promise,它可以是字面上的任何东西)

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