How to hook up SignalR with an Angular 7 application

后端 未结 4 1391
情话喂你
情话喂你 2021-02-01 23:52

I simply cannot figure out how to make a signalr connection from Angular.

Using the following tutorial at https://docs.microsoft.com/en-us/aspnet/signalr/overview/gettin

4条回答
  •  春和景丽
    2021-02-02 00:19

    • Angular app

    Install signalR package

    npm i @aspnet/signalr --save

    import { Component, OnInit } from '@angular/core';
    import { HubConnection } from '@aspnet/signalr';
    import * as signalR from '@aspnet/signalr';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent implements OnInit {
    
      private hubConnection: HubConnection;
    
      public ngOnInit() {
        this.hubConnection = new signalR.HubConnectionBuilder()
          .withUrl("http://localhost:50930/pushNotification").build();
    
        this.hubConnection.start().then(() => {
          console.log("connection started");
        }).catch(err => console.log(err));
    
        this.hubConnection.onclose(() => {
          debugger;
          setTimeout(() => {
            debugger;
            this.hubConnection.start().then(() => {
              debugger;
              console.log("connection started");
            }).catch(err => console.log(err));
          }, 5000);
        });
    
        this.hubConnection.on("clientMethodName", (data) => {
          debugger;
          console.log(data);
        });
    
        this.hubConnection.on("WelcomeMethodName", (data) => {
          debugger;
          console.log(data);
          this.hubConnection.invoke("GetDataFromClient", "user id", data).catch(err => console.log(err));
        });
      }
    
      public stopConnection() {
        this.hubConnection.start().then(() => {
          console.log("stopped");
        }).catch(err => console.log(err));
      }
    }
    
    • Web API with netcoreapp2.2

      Install Microsoft.AspNetCore.SignalR

    Startup.cs

    Client is running on port 4200 ("http://localhost:4200").

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    
    namespace SignalRWebApp
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
                services.AddCors(option =>
                {
                    option.AddPolicy("CorsPolicy", builder =>
                             builder.WithOrigins("http://localhost:4200")
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials());
                });
                services.AddSignalR();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseCors("CorsPolicy");
    
                app.UseSignalR(routes =>
                {
                    routes.MapHub("/pushNotification");
                });
    
                app.UseHttpsRedirection();
                app.UseMvc();
            }
        }
    }
    

    SignalHub.cs

    using Microsoft.AspNetCore.SignalR;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace SignalRWebApp
    {
        public class SignalHub : Hub
        {
            public void GetDataFromClient(string userId, string connectionId)
            {
                Clients.Client(connectionId).SendAsync("clientMethodName", $"Updated userid {userId}");
            }
    
            public override Task OnConnectedAsync()
            {
                var connectionId = Context.ConnectionId;
                Clients.Client(connectionId).SendAsync("WelcomeMethodName", connectionId);
                return base.OnConnectedAsync();
            }
    
            public override Task OnDisconnectedAsync(Exception exception)
            {
                var connectionId = Context.ConnectionId;
                return base.OnDisconnectedAsync(exception);
            }
        }
    }
    

    Now send signalR message like the below example

    [Route("api/[controller]")]
        [ApiController]
        [EnableCors("CorsPolicy")]
        public class ValuesController : ControllerBase
        {
            private IHubContext _hub;
            public ValuesController(IHubContext hub)
            {
                _hub = hub;
            }
    
            // GET api/values
            [HttpGet]
            public ActionResult> Get()
            {
                _hub.Clients.All.SendAsync("clientMethodName", "get all called");
                return new string[] { "value1", "value2" };
            }
    
            // GET api/values/5
            [HttpGet("{connectionId}")]
            public ActionResult Get(string connectionId)
            {
                _hub.Clients.Client(connectionId).SendAsync("clientMethodName", "get called");
                return "value";
            }
        }
    }
    

    Github

提交回复
热议问题