如何将全局或外部函数调用为子函数?

时间:2019-05-29 04:08:35

标签: typescript websocket atmosphere atmosphere.js

我正在使用下面的代码,并且在我调用 onMessageRender() 函数时,它说"this is not a function"

  

request =新的Atmosphere.AtmosphereRequest(); //全局函数

在ngONinIt中调用以下代码

  

this.createSSE();

//Main function 
 createSSE(){ this.request.onMessage = function (response) {
        console.log('request.onMessage trigger');
         try {
           let jsonData = JSON.parse(message);
          console.log('Normal Message JSON this.request.util', jsonData);  
          this.onMessageRender();    
        }catch (e) {
           console.log('Error in websocket onmessage: ', e);
           return;
         } }

全局创建以下功能

onMessageRender(){

}

如果您需要更多信息,请告诉我。谢谢!

2 个答案:

答案 0 :(得分:0)

假设这是一个Angular /打字稿问题,

如果将createSSE声明为Angular模块的一部分,并且如果onMessageRender()是未声明为Angular模块的一部分的全局函数,则调用onMessageRender()应该没有{ {1}},因为this可能不是声明onMessageRender()的对象的一部分。

如果createSSE确实是同一对象的一部分,我认为需要更多细节来回答您的问题。

答案 1 :(得分:0)

我想回答我自己的问题,因为经过很多斗争。我有我的工作解决方案。

我需要将我的Normal / Old样式函数转换为Fat Arrow函数,因为 Arrow函数始终具有this引用,并且该引用可用于该类对象。

旧(无效)

  

this.request.onMessage =函数(响应){...}

新功能(工作中)

  

this.request.onMessage =(响应)=> {...}

在进行了上述更改之后,现在它正在接受其中的所有其他功能。

感谢大家的时间和支持!