我想连接到SignalR Hub并使用Angular 4检索数据。 如果你能提供一个如何实现这一目标的样本,我将不胜感激。
答案 0 :(得分:10)
在这里,我想为您提供我在项目中使用的SignlR服务。希望这有助于您理解。
import { CommonService } from './commonService';
import { AuthSettings } from '../authSettings';
import { Injectable, EventEmitter } from '@angular/core';
declare const $: any;
@Injectable()
export class SignalRService {
private connectionId;
private authData;
private signalRConnectionId;
private proxy: any;
private connection: any;
private tryingToReconnect = false;
public ExpiredBidStatus: EventEmitter<any>;
public ActivatedBid: EventEmitter<any>;
public Notification: EventEmitter<any>;
constructor(private commonSvc: CommonService) {
this.ActivatedBid = new EventEmitter<any>();
this.ExpiredBidStatus = new EventEmitter<any>();
this.Notification = new EventEmitter<any>();
}
public initialize(): void {
this.connection = $.hubConnection(AuthSettings.apiServiceBaseUri);
this.proxy = this.connection.createHubProxy('crowneStockHub');
this.setToken();
this.proxy.on('broadcastExpiredBidStatus', (bidId) => {
this.ExpiredBidStatus.emit(bidId);
});
this.proxy.on('broadcastActivatedBid', (bid) => {
console.log('activated bid');
this.ActivatedBid.emit(bid);
});
this.proxy.on('broadcastNotification', (notification) => {
console.log('notification');
console.log(notification);
this.Notification.emit(notification);
});
this.proxy.on('broadcastTimeOut', () => {
this.initialize();
});
this.stopConnection();
this.connection.start().done((data: any) => {
console.log('Now connected');
this.connectionId = this.connection.id;
this.commonSvc.signalRConnectionId = this.connectionId;
}).fail((error: any) => {
console.log('Could not connect ' + error);
});
this.connection.reconnecting(() => {
this.tryingToReconnect = true;
});
this.connection.reconnected(() => {
this.tryingToReconnect = false;
});
this.connection.error((error) => {
this.initialize();
});
this.connection.disconnected(() => {
if (this.tryingToReconnect) {
setTimeout(() => {
this.initialize();
}, 5000);
}
});
}
setToken() {
this.authData = window.localStorage.getItem('authorizationData');
if (this.authData) {
const token = this.authData.token;
$.signalR.ajaxDefaults.headers = { Authorization: 'Bearer ' + token };
}
};
stopConnection() {
this.connection.stop();
};
getConnection() {
return this.connectionId;
};
}
答案 1 :(得分:0)
感谢Jota.Toledo, c-sharpcorner.com/article为我工作。 除此之外,我还修改了OwinStartup,如下所示。
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.MapSignalR();