Чат с SignalR |Угловой 8 |ASP.NET-Core 2.1 - PullRequest
0 голосов
/ 13 октября 2019

Я пытаюсь повторить пример с чатом. Такой вот . Но, как я понимаю, у меня проблема с адресом моего хозяина. Это то, что у меня есть, когда мой компонент запустился.

enter image description 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));
}
}

Имеется файл jSts для запуска параметров.

enter image description here

В чем проблема?

1 Ответ

0 голосов
/ 16 октября 2019

Я пытался создать хаб-сервер SignalR и Angular клиент в одном проекте с нуля, используя один и тот же код для создания хаб-сервера и настройки SignalR.

А для Angular client я обнаружил, что этот пакет ' @ aspnet / signalr-client ' устарел, поэтому вместо него я использую ' @ aspnet / signalr '.

Проект работает на моей стороне без ошибок, если возможно, вы можете создать новый проект или использовать ' @ aspnet / signalr ', чтобы создать клиент SignalR 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));
  }
}

Результат теста

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...