Angular not subscribing to SignalR message

Viewed 855

I'm trying to subscribe to the message I sent, but it keep returning null in the browser

enter image description here

The SignalR connection is already established and I can send messages, but it's not subscribing to any changes. Why is that?

SignalR Service

import { Injectable, EventEmitter } from "@angular/core";
import * as signalR from "@aspnet/signalr";
import { SignalViewModel } from "./signal-view-model";
import { HttpClient, HttpParams } from "@angular/common/http";


@Injectable({
  providedIn: "root"
})
export class SignalRService {
  private hubConnection: signalR.HubConnection;
  signalReceived = new EventEmitter<SignalViewModel>();

  constructor(private http: HttpClient) {
    this.buildConnection();
    this.startConnection();
  }

  private buildConnection = () => {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl("http://localhost:7070/api")
      .build();
  }
  sendMessage(message: SignalViewModel) {

    this.http.post('http://localhost:7070/api/messages', message).subscribe(data => console.log(data));
  }
  private startConnection = () => {
    this.hubConnection
      .start()
      .then(() => {
        console.log("Connection Started...");
        this.registerSignalEvents();
      })
      .catch(err => {
        console.log("Error while starting connection: " + err);

        //if you get error try to start connection again after 3 seconds.
        setTimeout(function () {
          this.startConnection();
        }, 3000);
      });
  }

  private registerSignalEvents() {
    this.hubConnection.on("SignalMessageReceived", (data: SignalViewModel) => {
      this.signalReceived.emit(data);
    });
  }
}

SignalViewModel

export class SignalViewModel {
  clientuniqueid: string;
  type: string;
  message: string;
  date: Date;
}

component

  notificationSubscription: Subscription;

  ngOnInit() {

 this.signalRService.signalReceived.subscribe(msg => {
      this.messages.push(msg);
      console.log(this.messages)

    });

//I also tried it like the following, but same issue

 this.notificationSubscription = this.signalRService.signalReceived.subscribe(msg => {
      this.messages.push(msg);
      console.log(this.messages)

    })

...

How can I get it to subscribe successfully? I appreciate any help!

2 Answers

You can try this approach. On the signalR service create an EventEmitter:

@Output() onSignalRMessage: EventEmitter<any> = new EventEmitter();

And call the private function to receive data as SignalViewModel.

private registerSignalEvents() {
    this.hubConnection.on("SignalMessageReceived", (data: SignalViewModel) => {
      this.newMessage(data as SignalViewModel);
    });
  }

private newMessage(data: SignalViewModel) {
    this.onSignalRMessage.emit(data);
  }

Then on the component:

ngOnInit(): void {
  /** Invoked when is received new data*/
  this.signalRService.onSignalRMessage.subscribe((data: SignalViewModel) => {
    console.log(data);
  });

And don't forget add the signalRService to the constructor.

Update1: After running your code, I can successfully connect to my local signalR service and also to the Azure SignalR Service and I'm receiveing data. As you can see the problem is not connecting and not with the received data.

Console logs

You should see what is wrong with the Azure functions.

Also I would recommend to change your client side SignalR package from @aspnet/signalr that is now obsolete to the new @microsoft/signalr package.

You have to use obsarvable, in your case you will have something like this:

In your service:

  import { BehaviorSubject } from 'rxjs';

  // In your declaration
  private source = new BehaviorSubject();
  signalReceived = this.source.asObservable();

  private registerSignalEvents() {
    this.hubConnection.on("SignalMessageReceived", (data: SignalViewModel) => {
      this.source.next(data)
    });
  }

in your component:

ngOnInit() {
    this.signalRService.signalReceived.subscribe(data => console.log(data))
 }
Related