带有ng2-stompjs配置的Angular 7

时间:2019-02-21 11:00:59

标签: angular angular7 stomp

我正在遵循以下网页中的教程:https://stomp-js.github.io/guide/ng2-stompjs/2018/11/04/ng2-stomp-with-angular7.html

一切都很好,直到我得到必须外部化应用程序的所有配置(包括websocket URL)的那一部分。由于我对Angular的了解不足,因此很难做到这一点。问题是,在教程中它是硬编码的:

android:weight=

我准备了用于获取API网址的此类:

export const myRxStompConfig: InjectableRxStompConfig = {
// Which server?
brokerURL: 'ws://127.0.0.1:15674/ws',

我正在尝试类似这样的事情:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AppConfig {

  private config: object = null;
  private env: object = null;

  constructor(private http: HttpClient) {}

  public getConfig(key: any) {
    return this.config[key];
  }

  public getEnv(key: any) {
    return this.env[key];
  }

  getConfigs(): Promise<Object> {
    return new Promise((resolve, reject) => {
    this.http.get('assets/config/env.json').subscribe((envResponse: any) 
=> {
    this.env = envResponse;
    let request: any = null;
    switch (envResponse.env) {
      case 'production':
      {
        request = this.http.get(
          'assets/config/api.' + this.getEnv('env') + '.json'
        );
      }
        break;

      case 'development':
      {
        request = this.http.get(
          'assets/config/api.' + this.getEnv('env') + '.json'
        );
      }
        break;

      case 'default':
      {
        console.error('Environment file is not set or invalid');
        resolve(true);
      }
        break;
    }
    if (request) {
      request.subscribe(responseData => {
        this.config = responseData;
        resolve(true);
      });
    } else {
      console.error('Env config file "env.json" is not valid');
      resolve(true);
    }
  });
});
}
}

}

但是没有运气。你能指出我正确的方向吗?如何实现将InjectableRxStompConfig中的brokerURL外部化。

谢谢, 城市

3 个答案:

答案 0 :(得分:1)

我想我很讨厌看到明显的东西,所以我将为我的问题发布答案。 我不得不将其放入ngModule:

    {
      provide: InjectableRxStompConfig,
      useClass: Stomp,
      deps: [AppConfig]
    },

并按如下方式编写Stomp类:

import {AppConfig} from "./app.config";

export class Stomp {

  public brokerURL = null;
  public heartbeatIncoming: 0; // Typical value 0 - disabled
  public heartbeatOutgoing: 0; // Typical value 20000 - every 20 seconds
  public reconnectDelay: 5000;

  constructor(private appConfig: AppConfig) {
    this.brokerURL = this.appConfig.getConfig('openbatonWS') + '/websocketRD/websocket';
  }
}

答案 1 :(得分:1)

感谢@ bam123!

我通过以下方式实现它:

export class MyRxStompConfig extends InjectableRxStompConfig {
    constructor(private config: ConfigService) {
        super();
        this.brokerURL = this.config.brokerURL;
        this.heartbeatIncoming = 0;
        this.heartbeatOutgoing = 10000;
        this.reconnectDelay = 500;
    }
}

然后将以下内容放入我的app.module

{ provide: InjectableRxStompConfig, useClass: MyRxStompConfig, deps: [ConfigService] }

答案 2 :(得分:0)

我为RxStompService写了一个包装器服务类,并定义了连接,销毁,发送和接收消息的方法。因此,无论何时调用此服务。您可以动态发送配置详细信息。

export class QueueMessageService implements OnInit, OnDestroy{
  private rxStompConfig: InjectableRxStompConfig
  private rxStompService: RxStompService;
  constructor() { }

  ngOnInit() {}

  fetchConfig(url :string): InjectableRxStompConfig {
    const myRxStompConfig: InjectableRxStompConfig = {
        // Which server?
        brokerURL: url,

        // Headers
        // Typical keys: login, passcode, host
        connectHeaders: {
          login: 'guest',
          passcode: 'guest'
        },

        // How often to heartbeat?
        // Interval in milliseconds, set to 0 to disable
        heartbeatIncoming: 0, // Typical value 0 - disabled
        heartbeatOutgoing: 0, // Typical value 20000 - every 20 seconds

        // Wait in milliseconds before attempting auto reconnect
        // Set to 0 to disable
        // Typical value 5000 (5 seconds)
        reconnectDelay: 200,

        // Will log diagnostics on console
        // It can be quite verbose, not recommended in production
        // Skip this key to stop logging to console
        debug: (msg: string): void => {
          console.log(new Date(), msg);
        }
      };
      return myRxStompConfig;
  }


  public connect(url: string) {
    this.rxStompConfig = this.fetchConfig(url);
    this.rxStompService = rxStompServiceFactory(this.rxStompConfig);
    this.rxStompService.activate;
  }

  public disconnect() {
    this.rxStompService.deactivate;
  }


  receiveMessage(topicName: string) {
    return this.rxStompService.watch(topicName);
  }

  sendMessage(topicName: string, message: string,createdBy: string) {
    var messageJson = {
        'Date': `${new Date}`,
        'Message':message,
        'CreatedBy':createdBy
     }
    return this.rxStompService.publish({destination: topicName, body: JSON.stringify(messageJson)});

  }


  ngOnDestroy() {
    this.rxStompService.deactivate;
  }
}

然后从组件中调用服务,如下所示。我已经在此处对URL和主题名称进行了硬编码,但是我们可以从config或Rest-service等中检索值,


@Component({
  selector: 'app-messages',
  templateUrl: './messages.component.html',
  styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit, OnDestroy {
  public receivedMessages: string[] = [];
  private topicSubscription: Subscription;


  constructor(private queueMessageService: QueueMessageService) { }

  ngOnInit() {
    this.queueMessageService.connect(this.getQueueURL());
    this.topicSubscription = this.queueMessageService.receiveMessage(this.getTopicName()).subscribe((message: Message) => {
      this.receivedMessages.push(message.body);
    });
  }

  ngOnDestroy() {
    this.topicSubscription.unsubscribe();
    this.queueMessageService.disconnect();
  }

   onSendMessage() {
     const message = `Paddy Message generated`;
     this.queueMessageService.sendMessage(this.getTopicName(),message,'user1');
  }

  getQueueURL(): string {
    return 'ws://127.0.0.1:61614//ws';
  }

  getTopicName(): string {
    return '/topic/demo';
  }
}