Перекрестное уведомление от IOS до веб-приложения Angular 4 с использованием signalR - PullRequest
0 голосов
/ 08 января 2019

Я работаю над проектом, в котором я использую центральные сервисы Web api 2, используя как для IOS, так и для Angular 4. Я хочу отразить изменения в веб-приложении, когда пользователь делает ставку на любом аукционе. Поскольку я делаю это в угловом веб-приложении 4 с использованием сервиса signalR, и он работает нормально, я обновляю количество ставок и текущую сумму, используя signalR. Но проблема заключается в том, как отразить последнюю ставку для веб-приложения, когда пользователь делает ставку из приложения IOS. Вот мой код на стороне сервера

     [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.

...