我已经按照ng2-signalr上的说明进行操作,这是我想出的:
app.module.ts
import { SignalRModule } from 'ng2-signalr';
import { SignalRConfiguration } from 'ng2-signalr';
export function createConfig(): SignalRConfiguration {
const config = new SignalRConfiguration();
config.hubName = 'MyHub';
config.qs = { user: 'donald' };
config.url = 'http://localhost:8089/';
config.executeEventsInZone = true; // optional, default is true
config.executeErrorsInZone = false; // optional, default is false
config.executeStatusChangeInZone = true; // optional, default is true
return config;
}
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule,
SignalRModule.forRoot(createConfig)
],
app.component.ts
import { Component, OnInit } from '@angular/core';
import { ServicesService } from 'src/services.service';
import '../../node_modules/signalr/jquery.signalR.js';
import { SignalR,
BroadcastEventListener,
IConnectionOptions,
SignalRConnection } from 'ng2-signalr';
declare var $:any;
// import 'expose-loader?jQuery!jquery';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'client';
options: IConnectionOptions = { hubName: 'MyHub' };
onMessageSent$ = new BroadcastEventListener<string>('heartbeat')
public _connection: SignalRConnection
nick = '';
message = '';
messages: string[] = [];
constructor(
private ser: ServicesService,
private _signalR: SignalR,
){}
ngOnInit(): void {
// this._signalR.connect(this.options);
this._signalR.connect().then((c) => {
console.log(c);
});
this._connection.listen(this.onMessageSent$);
this.onMessageSent$.subscribe((chatMessage: string) => {
console.log(chatMessage);
});
}
}
它可以很好地连接到信号服务器。但是在我的控制台中,我得到了这个错误
而且我不能从服务器中注销数据。非常感谢您的帮助。谢谢。
答案 0 :(得分:1)
基本上,您需要订阅“连接”
public _connection: SignalRConnection
nick = '';
message = '';
messages: string[] = [];
private signalRSubscriptions: Subscription[] = [];
configuration: any = {
// your config object here
};
constructor(
private ser: ServicesService,
private _signalR: SignalR,
){}
ngOnInit(): void {
this.connect();
}
connect(): void {
this._signalR.connect(this.configuration).then((c) => {
this._connection = c;
c.listen(this.onMessageSent$);
this.signalRSubscriptions.push(onMessageSent$.subscribe((chatMessage: string) => {
console.log(chatMessage);
}));
}).catch((error) => {
// this.reconnect();
});
});
答案 1 :(得分:0)
您没有为this._connection
分配任何内容。在github上的ng2-singalr上快速阅读自述文件之后,我相信您需要执行以下操作:
public _connection: SignalRConnection
nick = '';
message = '';
messages: string[] = [];
constructor(
private ser: ServicesService,
private _signalR: SignalR,
){}
ngOnInit(): void {
this._connection = this._signalR.connect()
this._connection.listen(this.onMessageSent$);
this.onMessageSent$.subscribe((chatMessage: string) => {
console.log(chatMessage);
});
}
}