user1361529
user1361529

Reputation: 2697

Typescript - passing a callback to an @injectible service that does subscribe

I have an @Injectable service in Angular2 that does this:

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

I'd like the doMyFancyShmancyFoo() to be a parameter that I can pass to startAllSensors from my calling component, which means I want to do something like:

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 }

I understand I can use @Input and @Output between components, but not sure how to apply that when its a service.

Upvotes: 2

Views: 976

Answers (1)

vinays84
vinays84

Reputation: 422

Typescript methods within services can accept functions as parameters:

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

Then the following call from your component should work:

this.sensors.startAllSensors(accCallback, gyroCallback);

Upvotes: 2

Related Questions