Búsqueda de sitios web

angular - Typescript - pasar un callback a un servicio @injectable que hace subscribe


Tengo un servicio @Injectable en Angular2 que hace esto:

startAllSensors() {
  this.accSub = this.deviceMotion.watchAcceleration({ frequency: this.freq }).subscribe((acceleration: DeviceMotionAccelerationData) => {
    doMyFancyShmancyFoo();
  });

  // listen to gyro data
  this.gyrSub = this.gyroscope.watch({ frequency: this.freq }).subscribe((gyroscope: GyroscopeOrientation) => {
    doMyFancyShmancyFoo();
  });
}

Me gustaría que doMyFancyShmancyFoo() fuera un parámetro que pueda pasar a startAllSensors desde mi componente que llama, lo que significa que quiero hacer algo como:

calling.ts

this.sensors.startAllSensors(accCallback, gyroCallback);
accCallback (data) { // will be called each time the injectable service has data to report }
gyroCallback (data) { // will be called each time the injectable service has data to report }

Entiendo que puedo usar @Input y @Output entre componentes, pero no estoy seguro de cómo aplicarlo cuando se trata de un servicio.

Respuesta #1

Los métodos de Typescript dentro de los servicios pueden aceptar funciones como parámetros:

  startAllSensors(accCallback: Function, gyroCallback: Function) {
      this.accSub = this.deviceMotion.watchAcceleration({ frequency: this.freq })
          .subscribe((acceleration: DeviceMotionAccelerationData) => {
              accCallback();
          });
      this.gyrSub = this.gyroscope.watch({ frequency: this.freq })
          .subscribe((gyroscope: GyroscopeOrientation) => {
              gyroCallback();
          });
  }

Entonces la siguiente llamada desde tu componente debería funcionar:

this.sensors.startAllSensors(accCallback, gyroCallback);