Angular : Unable to pass API url in SignalR HubCon

2020-07-18 01:52发布

I have developed a project in Angular6. There is a requirement to develop section for live chat. For that I am using SignalR in my asp.net core Web Apiproject. Now I want to use this Web Api reference in my Angular project.

I am using this link.

But while providing the Web Api url in App.Component.ts, I am getting below error :

Constructor of class 'HubConnection' is private and only accessible within the class declaration.

App Component.ts :

import { HubConnection } from '@aspnet/signalr';
import { Message } from 'primeng/api';

export class AppComponent implements OnInit {
  public _hubConnection: HubConnection;
  msgs: Message[] = [];
  constructor() {   
  }
  ngOnInit() {
    this._hubConnection = new HubConnection('http://localhost:1874/notify'); // getting error on this line.

Edit : tried below code :-

Modified App.Component.ts :

import { HubConnection } from '@aspnet/signalr';
import * as signalR from '@aspnet/signalr';
import { Message } from 'primeng/api';

export class AppComponent implements OnInit {
  public _hubConnection: HubConnection;
  msgs: Message[] = [];
  constructor() {   
  }
  ngOnInit() {       
    this._hubConnection = new signalR.HubConnectionBuilder()
          .withUrl('http://localhost:1874/notify')
          .configureLogging(signalR.LogLevel.Information)
          .build();

Error :

Failed to load http://localhost:1874/notify/negotiate: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

3条回答
我只想做你的唯一
2楼-- · 2020-07-18 02:37

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 :('));

  }
查看更多
疯言疯语
3楼-- · 2020-07-18 02:41

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

    ...
}
查看更多
小情绪 Triste *
4楼-- · 2020-07-18 02:44

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.

查看更多
登录 后发表回答