处理Angular 2中的CometD通道无效

时间:2017-05-17 08:44:52

标签: javascript angular typescript cometd

在Angular2和Typescript中的一些宝贝步骤之后,我决定编写使用普通javascript CometD库的应用程序。这个应用程序应该只从CometD频道获取数据,并以某种方式将它们呈现给用户。

基本上,我已经参考CometD js库创建了以下简单组件。

import { Component } from '@angular/core';
import * as cometd from '../cometd/cometd';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

   title = 'app works!';
   cometD: any;

  constructor() {
    console.log("Starting cometD service ...");
    this.cometD = new cometd.CometD();
    this.cometD.configure({ url: '/services/cometd', logLevel: 'debug', requestHeaders: { "userID": 555 } });
    this.title = "CometD demo";
    this.cometD.handshake();
    this.subscribe()
  }


  subscribe() {
    this.cometD.subscribe('/mychannel', (message)=> this.mychannelHandler(message));
  }

  mychannelHandler(message) {
    console.log("MESSAGE FROM SERVER RECIEVED: " + message + ", data: " + message.data);
    this.title = message.data;
  }


}

当我运行它时,来自cometD的控制台中有调试消息 - 连接正常,已经添加了对通道的订阅,以及一些输出,即有一些数据到来。 BUT。

永远不会调用mychannelHandler。消息永远不会传递到控制台,并且未设置标题变量。我错过了什么?

非常感谢您提供任何有用的答案。

1 个答案:

答案 0 :(得分:0)

您不是在这里致电this.mychannelHandler。您对subscribe的回调不会调用this.mychannelHandler

subscribe() {
  this.cometD.subscribe('/mychannel', () => this.mychannelHandler); 
}

将其更改为:

this.cometD.subscribe('/mychannel', this.mychannelHandler); 
// OR
this.cometD.subscribe('/mychannel', (message) => this.mychannelHandler(message));