代码之家  ›  专栏  ›  技术社区  ›  bob.mazzo

如何将信号机与Angular 7应用程序连接起来

  •  1
  • bob.mazzo  · 技术社区  · 7 年前

    我根本不知道如何从角度建立信号机连接。

    https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc

    我添加了一个新的 SignalR 2.4.0将项目转移到现有项目。vs2017中的Net 4.6解决方案。

    Angular 7 我添加了 信号员 包裹通过 npm install @aspnet/signalr

    现在,我正在尝试在客户端和服务器之间建立一个简单的连接,但不知道如何建立初始连接。

    我的前端不断抛出一个异常:

     core.js:15714 ERROR Error: Uncaught (in promise): Error: Cannot send data if the connection is not in the 'Connected' State.
    

    在我的前端搜索组件中,我添加了一些用于测试的字段:

    <mat-form-field>
        <input matInput placeholder="message" [(ngModel)]="message">
    </mat-form-field>
    <button mat-button type="button" (click)="sendMessageToServer()"><span>Send</span></button>            
    <p *ngFor="let m of messages">{{m}}</p>

    在我的ts文件中:

    // import other components/services here..
    import { HubConnection, HubConnectionBuilder} from '@aspnet/signalr';
    
    @Component({
      selector: 'app-my-search',
      templateUrl: './my-search.component.html',
      styleUrls: ['./my-search.component.scss']
    })
    export class MySearchComponent implements OnInit {
    
    public hubConnection: HubConnection;
      public messages: string[] = [];
      public message: string;
    
       constructor() { }
       
       
      ngOnInit() {
       
        // SIGNALR MESSAGE HUB
        let builder = new HubConnectionBuilder();
        this.hubConnection = builder.withUrl('/SynBroadcastHub/BroadcastMessage').build();  // see startup.cs
        this.hubConnection.on('notifyUser', (message) => {
          this.messages.push(message);
          console.log(message);
        });
        this.hubConnection.start();
      }
    
      // signalr, send msg from client
      sendMessageToServer() {
        this.hubConnection.invoke('MessageToServer', this.message);
        this.message = '';
      }
    
    
    }

    SignalR Hub Class (v2) 文件,广播中心。反恐精英

    using Microsoft.AspNet.SignalR;
    
    namespace SynBroadcastHub
    {
        public class BroadcastHub : Hub
        {        
            /// Message to client 
            public void BroadcastMessage(string data)
            {
                Clients.Caller.notifyUser(data);
            }
        
            
            /// Message from client application; broadcast to all clients if requested.                
            public void MessageToServer(string data, bool notifyAllClients = false)
            {
                if (notifyAllClients)
                {
                    Clients.All.NotifyAllClients(data);
                }
            }
        }
    }

    Startup.cs

    using Microsoft.Owin;
    using Microsoft.AspNet.SignalR;
    using Owin;
    
    [assembly: OwinStartup(typeof(SynBroadcastHub.Startup))]
    
    namespace SynBroadcastHub
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                HubConfiguration cfg = new HubConfiguration();
                app.MapSignalR<PersistentConnection>("BroadcastHub/BroadcastMessage");
                app.MapSignalR(cfg);
                app.MapSignalR();
    
                //app.MapSignalR<NotifyHub>("notify"); ???
            }
             public override Task OnDisconnected(bool stopCalled)
            {
                return Clients.All.leave(Context.ConnectionId, System.DateTime.Now.ToString());
            }
    
            public override Task OnConnected()
            {
                return Clients.All.joined(Context.ConnectionId, DateTime.Now.ToString());
            }
    
            public override Task OnReconnected()
            {
                return Clients.All.rejoined(Context.ConnectionId, DateTime.Now.ToString());
            }
        }
    }
    2 回复  |  直到 7 年前
        1
  •  34
  •   pol    7 年前

    我花了两天的时间想弄明白同样的事情。我终于成功了,以下是我必须做的几件事:

    1) 您注意到使用 @aspnet/signalr 包装不正确。Net框架,这是正确的。你需要 signalr npm install signalr ).

    SignalR 依赖于 jQuery 你 要包括jQuery 之前 包括信号器脚本。在 angular.json scripts 第节,您需要包括:

    "./node_modules/jquery/dist/jquery.js", "./node_modules/signalr/jquery.signalR.js"

    jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file

    叫你写 import * as $ from "jquery" 不 about global scripts ,使用 import module 把它装进箱子里 vendor.js 通过运行 ng build 命令这是一个问题的原因,因为jQuery将首先从您的数据库中加载。json,然后加载signalR,然后从供应商处加载模块。js将重新加载jQuery并从signalR取消附加到jQuery的所有事件。

    3) 因为你注意到你在用这个。Net核心版本的信号器,您将无法访问 HubConnectionBuilder 尝试在角度组件中实例化新连接时。

    $ 注意:如果您从ts文件中获得构建或编译时错误,请确保已包含 @types/signalr 和 @types/jquery 来自npm

    $.hubConnection("your-url-here/signalr") 。运行时,它将连接到服务器的集线器。 注意:我将结果存储为一个名为 hubConnection 在我的角分量中

    [HubName("YourHubName")] .所以你的情况是你的。cs文件在顶部看起来像这样:

    [HubName("Broadcast")]    
    public class BroadcastHub : Hub
    

    你很可能必须在你的简历顶部写上这一点。cs文件: using Microsoft.AspNet.SignalR.Hubs;

    在实例化新的HUB连接后的下一行,写下:

    this.hubConnection.createHubProxy("yourHubName"); .

    就你而言, this.hubConnection.createHubProxy("broadcast");

    创建代理后,可以附加侦听器以侦听服务器发出的事件,也可以从组件调用服务器函数。

    example

    简短回答:使用 proxy.on('eventname') 到 从服务器中删除事件,并使用 proxy.invoke('eventname') 呼叫 通过角度组件在轮毂上执行功能。

    最后,在您的cs文件中添加一些注释。在我的创业公司。cs,我唯一能做的就是映射信号器 app.MapSignalR()

        2
  •  2
  •   Narottam Goyal    6 年前
    • 角度应用程序

    安装信号器包

    npm i@aspnet/signal——保存

    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));
      }
    }
    
    • netcoreapp2。2.

      微软AspNetCore。信号员

    客户端正在端口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<SignalHub>("/pushNotification");
                });
    
                app.UseHttpsRedirection();
                app.UseMvc();
            }
        }
    }
    

    信号中心。反恐精英

    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);
            }
        }
    }
    

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

    Github

        3
  •  1
  •   Wietze    7 年前

    我自己正在研究这个课题,发现了npm包ng2信号。也许你可以做些调查?

        4
  •  1
  •   A. Roussos    7 年前

    您确定hubEndpoint是正确的吗?看起来轮毂是角度布线的一部分(从您编写它的方式判断)。 https://www.myapp.com/SynBroadcastHub/BroadcastMessage

    推荐文章