我正在一个项目中,我正在使用同时用于IOS和Angular 4的中央服务Web api2。我想在用户竞标时反映Web应用程序上的更改。当我在使用signalR服务的angular 4 Web应用程序中进行操作时,它的运行状况很好,我正在使用signalR更新出价和当前金额。但是问题是,当用户从IOS应用程序出价时,如何在Web应用程序上反映最新出价。这是我的代码服务器端
[Authorize(Roles = "Admin, Ultimate, Premium")]
[HttpPost]
[Route("BidAuction")]
public IHttpActionResult BidAuction(BidModel model)
{
if (model.ItemId == 0)
return Ok();
int res = _service.AddBid(UserId, model.ItemId, model.BidAmount);
if (res == 0)
{
return Ok(new { Success = false, Message = "Either Bid Amount is low or " });
}
else
{
PublishEvent("NewBid", "Auction_" + model.ItemId, model.BidAmount, res);
return Ok(new { Success = true, Message = "You should receive msg on signalR hub" });
}
}
private void PublishEvent(string eventName, string _channel, decimal BidAmount, int NumberOfBidders)
{
string jsonData = "";
try
{
jsonData = @"{
'BidAmount':" + BidAmount + ",'NumberOfBidders':" + NumberOfBidders + "}";
BidResponseModel model = new BidResponseModel();
model.NoOfBidders = NumberOfBidders;
model.BidAmount = BidAmount;
_context.Clients.Group(_channel).OnBid(model);
}
catch (Exception ex)
{
Helper.Helper.SendExcepToDB(ex, UserId, "Auction", "PublishEvent", jsonData);
throw ex;
}
}
[HubName("AuctionHub")]
public class AuctionHub : Hub
{
static HashSet<string> CurrentConnections = new HashSet<string>();
// [Authorize]
public void Send(string name, string message)
{
Groups.Add(Context.ConnectionId, name);
// Call the broadcastMessage method to update clients.
//Clients.All.broadcastMessage(name, message + " " + Context.ConnectionId);
Clients.All.broadcastMessage(name, message);
}
public void SendMessage(long userId)
{
Clients.All.broadcastMessage(userId);
}
public void SendNotification(long userId)
{
Clients.All.broadcastNotification(userId);
}
public void SendBidData()
{
Clients.All.broadcastAmount();
}
public override Task OnConnected()
{
//var ev = new ChannelEvent
//{
// ChannelName = "admin",
// Name = "user.connected",
// Data = new
// {
// Context.ConnectionId,
// Context.User
// }
//};
//Publish(ev);
return base.OnConnected();
}
public void JoinChannel(string ChannelName)
{
Groups.Add(Context.ConnectionId, ChannelName);
using (OffeYappContext ctx = new OffeYappContext())
{
ExceptionLogger log = new ExceptionLogger();
log.ExceptionMessage = "Channel Joined";
ctx.ExceptionLoggers.Add(log);
ctx.SaveChanges();
}
}
public override Task OnDisconnected(bool stopCalled)
{
// Clients.All.broadcastMessage("Event", "");
return base.OnDisconnected(stopCalled);
}
public Task Publish(ChannelEvent channelEvent)
{
//Clients.All.broadcastMessage("Event", channelEvent.Json
// );
Clients.Group(channelEvent.ChannelName).OnEvent(channelEvent.ChannelName, channelEvent);
return Task.FromResult(0);
}
}
Angular SignalR服务如下。
import {
Injectable,
EventEmitter
} from '@angular/core';
import {
Configuration
} from '../dataservice/app.constant.component';
// declare the global variables
declare var $: any;
@Injectable()
export class SignalRService {
// Declare the variables
private proxy: any;
private proxyName: string = 'AuctionHub';
private connection: any;
// create the Event Emitter
public messageReceived: EventEmitter<any> ;
public notificationReceived: EventEmitter<any> ;
public connectionEstablished: EventEmitter < Boolean > ;
public connectionExists: Boolean;
constructor(private _urlConf:Configuration) {
// Constructor initialization
this.connectionEstablished = new EventEmitter < Boolean > ();
this.messageReceived = new EventEmitter <any> ();
this.notificationReceived = new EventEmitter <any> ();
this.connectionExists = false;
// create hub connection
this.connection = $.hubConnection();
this.connection.url = this._urlConf.Server+'signalr';
//this.connection.hub.Authorization = 'Bearer '+localStorage.getItem('access_token');
// this.connection = $.hubConnection(this._urlConf.Server+'signalr',
// {useDefaultPath: false,
// 'Authorization':'Bearer '+localStorage.getItem('access_token')});
this.proxy = this.connection.createHubProxy('AuctionHub');
//this.connection = $.hubConnection(this._urlConf.Server);
// create new proxy as name already given in top
//this.proxy = this.connection.createHubProxy(this.proxyName);
// register on server events
this.registerOnServerEvents();
this.registerOnServerEventsMessage();
this.registerOnServerEventsNotification();
// call the connecion start method to start the connection to send and receive events.
this.startConnection();
}
// method to hit from client
public sendTime() {
// server side hub method using proxy.invoke with method name pass as param
this.proxy.invoke('GetRealTime');
}
// method to hit from client
public broadCastinfo(){
this.proxy.invoke('SendBidData');
}
public sendMessage(userId:number){
this.proxy.invoke('SendMessage',userId);
}
// Send Notification
public sendNotification(userId:number){
this.proxy.invoke('SendNotification',userId);
}
// check in the browser console for either signalr connected or not
private startConnection(): void {
this.connection.start({ jsonp: true }).done((data: any) => {
//console.log('Now connected ' + data.transport.name + ', connection ID= ' + data.id);
this.connectionEstablished.emit(true);
this.connectionExists = true;
}).fail((error: any) => {
console.log('Could not connect ' + error);
this.connectionEstablished.emit(false);
});
}
private registerOnServerEvents(): void {
this.proxy.on('broadcastAmount', (data: any) => {
// console.log('received in SignalRService: ' + JSON.stringify(data));
this.messageReceived.emit(data);
});
}
// this._hubConnection.on('BroadcastMessage', (type: string, payload: string) => {
// this.msgs.push({ severity: type, summary: payload });
// });
private registerOnServerEventsMessage(): void {
this.proxy.on('broadcastMessage', (data: any) => {
// console.log('received in SignalRService: ' + JSON.stringify(data));
this.messageReceived.emit(data);
});
}
private registerOnServerEventsNotification(): void {
this.proxy.on('broadcastNotification', (data: any) => {
this.notificationReceived.emit(data);
});
}
}
我想反映使用SignalR在Web应用程序上的最新出价。