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

标签 angular typescript

我在 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/

相关文章:

javascript - 如何在 Angular2 中捕获 HTTP 响应中的 400 bad request 错误

javascript - 覆盖 @angular/pwa ngsw-worker.js

javascript - 如何回到 Ionic 4

angular - 服务请求出现 404 错误。如何更改回复状态

jquery - 将 Bloodhound 导入 Angular 2 CLI 项目

javascript - 如何从 3rd 方库访问 Angular 组件

javascript - html存储safari隐身模式,angular2

reactjs - 使用 React 和样式化组件传播 Props TypeScript

typescript - 无法在 typescript 中导入节点js集群

angular - 模型驱动/ react 形式 : Auto mapping from Model to FormGroup ?