Angular Typescript-将回调传递给订阅的@injectible服务
我在Angular2中有一个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
@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);