首页 > 解决方案 > 带有 ng2-stompjs 配置的 Angular 7

问题描述

我在网页下关注教程: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。

谢谢, 城市

标签: angularangular7stomp

解决方案


谢谢@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] }

推荐阅读