【问题标题】:Angular 7 with ng2-stompjs configuration带有 ng2-stompjs 配置的 Angular 7
【发布时间】:2019-02-21 11:00:58
【问题描述】:

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

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

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

我准备了这个类来获取 API url:

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);
    }
  });
});
}
}

我正在尝试这样的事情:

export class Stomp {

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

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

}

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

谢谢, 城市

【问题讨论】:

    标签: angular angular7 stomp


    【解决方案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】:

      我想我已经厌倦了看到显而易见的事情,所以我会发布我的问题的答案。 我不得不把它放到 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';
        }
      }
      

      【讨论】:

        【解决方案3】:

        我为 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';
          }
        }
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-12-13
          • 1970-01-01
          • 2019-10-18
          • 2019-05-30
          • 2017-07-15
          • 2020-02-25
          • 2023-01-12
          相关资源
          最近更新 更多