2017-08-09 79 views
0

我有一段代码基本上监听加速计和陀螺仪,并执行一些操作。该代码工作得很好,但今天,我试图分裂这个功能分为两半:试图传递函数回调 - 回调不能正确执行

  • 听音部分被转移到服务(sensors.ts)
  • “关于数据的行为得到部分”被移到调用ts文件。

我面对的事实是,如果我在这可能需要一段时间的回调做任何操作,我没有收到后续回调的问题。

我面对我的地方回调的确是调用的问题,但调用里面我叫回来代码等功能导致应用刚刚起步“卡”(没有进一步的更新,订阅收到)

这里是代码:

sensors.ts

type SensorCallbackFunction = (data:any) => void;

注(我也使用尝试

startAllSensors(onAccData:SensorCallbackFunction, onGyroData:SensorCallbackFunction) { 
    // listen to acc. data 
    this.accSub = this.deviceMotion.watchAcceleration({ frequency: this.freq }).subscribe((acceleration: DeviceMotionAccelerationData) => { 
     console.log (">>>>>>>>>>>>> ACC CALLBACK") 
     onAccData(acceleration); 

    }); 

    // listen to gyro data 
    this.gyrSub = this.gyroscope.watch({ frequency: this.freq }) 
     .subscribe((gyroscope: GyroscopeOrientation) => { 
     console.log (">>>>>>>>>>>>> GYR CALLBACK") 
     onGyroData(gyroscope); 

     }); 

    } 

在调用该服务的组件,而不是上述类型):

this.sensors.startAllSensors(this.accDataReceived, this.gyroDataReceived); 

而在组件的功能:

accDataReceived(data) { 

    console.log ("acc data:"+JSON.stringify(data)); 
} 

gyroDataReceived(data) { 

    console.log ("gyr data:"+JSON.stringify(data)); 
} 

这个效果很好

但是,当我扩展任一回调的功能时,我停止获取后续通知(即,这些回调未被服务调用)。

但当下我延长或者回调的功能调用附加功能我停止获取后续的通知(即,这些回调服务不叫)

例如,我只是说此代码两个回调:

let dataClone = data.map(x => Object.assign({}, x)); 
this.doMoreStuff(); 

而繁荣,我停止获取订阅更新。我也尝试调用另一个绘制内部图表的函数,并且遇到同样的问题。

这让我相信我在某种程度上误解了函数回调应该如何工作,以及在回调代码中的期望是什么。

谢谢。

+0

你在哪里添加代码回调:所以修复时,通过像这样的回调引用是bindthis? – DeborahK

+0

不知道我是否正确理解你。回调是“accDataReceived”和“gyroDataReceived”。代码被添加到那里。谢谢。 – user1361529

+1

你可以建立一个演示这个问题的重拳吗? – DeborahK

回答

0

事实证明,这是this的问题。我误认了根本原因。

  • Component A被调用Service S功能与回调this.componentACallback
  • Service S通过调用this.doSomeOtherComponentAFunction()

正确调用的函数componentACallback需要

  • componentACallback内又Component A,在做更多的处理这是事情发生的地方

    this现在指向Service S(调用者),因此this.doSomeOtherComponentAFunction()无效。

    为什么这并没有返回一个错误,为什么内componentACallback搞砸了其他操作,如简单的console.logs是未知的 - 我只能猜测是它的地方搞砸了一些状态栈...

    无论如何,的

    this.ServiceS.serviceSFunction(this.componentACallback.bind(this))代替 this.ServiceS.serviceSFunction(this.componentACallback)