我在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
,这意味着我想做类似的事情:
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 }
我知道我可以在组件之间使用@Input
和@Output
,但不知道如何在服务时应用它。
答案 0 :(得分:1)
服务中的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);