与 SignalR 聊天 | Angular 8 | ASP.NET-核心2.1

Chat with SignalR | Angular 8 | ASP.NET-Core 2.1

我尝试在聊天中重复示例。 Such here。但据我所知,我的房东地址有问题。这是我的组件启动时所拥有的。

如您所见,我有两个地址。我只试了 /chat 但结果是一样的

我在 VS 中启动的应用程序。我不是作为一个单独的客户端开始的,并且 api-becked.

这是我的应用程序的网址,我在其中启动我的聊天组件。 http://localhost:59955/home/message

我的代码

public class ChatHub : Hub
{
public async Task Send(string name, string message)
{
    await this.Clients.All.SendAsync("sendToAll", name, message);
}
}

启动和我添加的内容。

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

我方法public void Configure(IApplicationBuilder app, IHostingEnvironment env)

app.UseSignalR(routes =>
    {
        routes.MapHub<Chat>("/chat");
    });

现客户端

export class ChatComponent implements OnInit {
// tslint:disable-next-line:variable-name
private _hubConnection: HubConnection;
nick = '';
message = '';
messages: string[] = [];

constructor() { }

ngOnInit() {
this.nick = window.prompt('Your name:', 'John');

this._hubConnection = new 
 HubConnectionBuilder().withUrl('http://localhost:59955/chat').build();

 this._hubConnection
  .start()
  .then(() => console.log('Connection started!'))
  .catch(err => console.log('Error while establishing connection :('));
 }


public sendMessage(): void {
 this._hubConnection.on('sendToAll', (nick: string, receivedMessage: string) 
 => {
  const text = `${nick}: ${receivedMessage}`;
  this.messages.push(text);
 });
 this._hubConnection
  .invoke('sendToAll', this.nick, this.message)
  .catch(err => console.error(err));
}
}

有 launchSettings json 文件。

什么问题?

我尝试在同一个项目中从头开始创建 SignalR 中心服务器和 Angular 客户端,使用相同的代码创建中心服务器和配置 SignalR。

对于 Angular 客户端,我发现这个包 '@aspnet/signalr-client' 已被弃用,所以我使用 '@ aspnet/signalr' 代替。

该项目在我这边运行良好,没有错误,如果可能,您可以创建新项目或使用'@aspnet/signalr'来构建SignalR Angular 客户端并检查它是否适合您。

Angular 客户

import { Component, OnInit } from '@angular/core';
import { HubConnection } from '@aspnet/signalr';
import signalR = require('@aspnet/signalr');

@Component({
  selector: 'app-signalrchatroom',
  templateUrl: './signalrchatroom.component.html',
  styleUrls: ['./signalrchatroom.component.css']
})
export class SignalrchatroomComponent implements OnInit {

  constructor() { }

  private _hubConnection: HubConnection;

  nick = '';
  message = '';
  messages: string[] = [];

  ngOnInit() {
    this.nick = window.prompt('Your name:', 'John');

    this._hubConnection = new signalR.HubConnectionBuilder()
      .withUrl("/chat")
      .build();

    this._hubConnection
      .start()
      .then(() => console.log('Connection started!'))
      .catch(err => console.log('Error while establishing connection :('));

    this._hubConnection.on('sendToAll', (nick: string, receivedMessage: string) => {
      const text = `${nick}: ${receivedMessage}`;
      this.messages.push(text);
    });
  }

  public sendMessage(): void {
    this._hubConnection
      .invoke('sendToAll', this.nick, this.message)
      .catch(err => console.error(err));
  }
}

测试结果