Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular Typescript-将回调传递给订阅的@injectible服务_Angular_Typescript - Fatal编程技术网

Angular Typescript-将回调传递给订阅的@injectible服务

Angular Typescript-将回调传递给订阅的@injectible服务,angular,typescript,Angular,Typescript,我在Angular2中有一个@Injectable服务,它可以: startAllSensors() { this.accSub = this.deviceMotion.watchAcceleration({ frequency: this.freq }).subscribe((acceleration: DeviceMotionAccelerationData) => { doMyFancyShmancyFoo(); }); // listen to gyro da

我在Angular2中有一个
@Injectable
服务,它可以:

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();
  });
}
我希望
doMyFancyShmancyFoo()
是一个参数,我可以从调用组件传递给
startAllSensors
,这意味着我要执行以下操作:

呼叫.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 }

我知道我可以在组件之间使用
@Input
@Output
,但不确定当它是服务时如何应用它。

服务中的Typescript方法可以接受函数作为参数:

  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();
          });
  }
那么来自组件的以下调用应该可以工作:

this.sensors.startAllSensors(accCallback, gyroCallback);