我在 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
,但不确定如何在其服务时应用它。
最佳答案
服务中的 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);
关于angular - Typescript - 将回调传递给订阅的 @injectible 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45591943/