Angular : Unable to pass API url in SignalR HubConnection

只谈情不闲聊 提交于 2019-12-04 09:34:16

They changed the constructors for SignalR Client HubConnection to no longer allow you to pass the route in the client constructor and made the HubConnection constructor private to enforce the change. Instead, you need to use the HubConnectionBuilder as follows:

new HubConnectionBuilder().withUrl("/YOURROUTEHERE").build();

You will want to import the HubConnectionBuilder in your header as follows:

import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';

In case it helps, I also just posted an update to my RxSignalR samples for @aspnet/signalr 1.0.2, RxJs 5.5.6 and Angular 6. Check out the ReactiveChat component for an example.

In your server code, are you using CORS?

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
    {
        builder.AllowAnyMethod()
               .AllowAnyHeader()
               .WithOrigins("http://localhost:4200")
               .AllowCredentials();
    }));

    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...

    app.UseCors("CorsPolicy");

    app.UseSignalR(routes =>
    {
        // your routes
    });

    ...
}

Try like this,

 private hubConnection: signalr.HubConnection;    
 message: string;
 ngOnInit() {
    this.hubConnection = new signalr.HubConnection('');

    this.hubConnection
      .start()
      .then(() => {
        console.log('Connection started!');
        this.hubConnection.on('ReceiveMessage', (message) => { 
          alert(message);
        });
      })
      .catch(err => console.log('Error while establishing connection :('));

  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!