我在网页下面看了以下教程: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 urls:
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的外部化?
谢谢你,城市
发布于 2019-02-22 16:55:43
我想我是太累了,看不到明显的东西,所以我会张贴我的问题的答案。我不得不把这个放到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';
}
}发布于 2020-03-04 17:24:52
谢谢@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] }发布于 2020-03-09 17:15:13
我为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';
}
}https://stackoverflow.com/questions/54805504
复制相似问题