经过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的控制台中有调试消息-连接正常,已经为该频道添加了订阅,并且输出了一些数据。但。

永远不会调用mychannelHandler。该消息永远不会传递到控制台,并且没有设置title变量。我想念什么?

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

最佳答案

您不是在这里呼叫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));

关于javascript - 在Angular 2中处理CometD channel 不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44019828/

10-09 06:12