Angular : Unable to pass API url in SignalR HubConnection

偶尔善良 提交于 2020-01-01 11:49:28

问题


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.


回答1:


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.




回答2:


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

    ...
}



回答3:


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

  }


来源:https://stackoverflow.com/questions/51112154/angular-unable-to-pass-api-url-in-signalr-hubconnection

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