Skip to content

Instantly share code, notes, and snippets.

@GrillPhil
Created May 23, 2018 08:33
Show Gist options
  • Save GrillPhil/50f59a6e5b8dafbc88440a059cd9a5b6 to your computer and use it in GitHub Desktop.
Save GrillPhil/50f59a6e5b8dafbc88440a059cd9a5b6 to your computer and use it in GitHub Desktop.
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { HubConnection } from '@aspnet/signalr';
import * as signalR from '@aspnet/signalr';
import { Observable } from "rxjs";
import { SignalRConnectionInfo } from "./signalr-connection-info.model";
import { map } from "rxjs/operators";
import { Subject } from "rxjs";
@Injectable()
export class SignalRService {
private readonly _http: HttpClient;
private readonly _baseUrl: string = "http://localhost:7071/api/";
private hubConnection: HubConnection;
messages: Subject<string> = new Subject();
constructor(http: HttpClient) {
this._http = http;
}
private getConnectionInfo(): Observable<SignalRConnectionInfo> {
let requestUrl = `${this._baseUrl}negotiate`;
return this._http.get<SignalRConnectionInfo>(requestUrl);
}
init() {
this.getConnectionInfo().subscribe(info => {
let options = {
accessTokenFactory: () => info.accessKey
};
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(info.endpoint, options)
.configureLogging(signalR.LogLevel.Information)
.build();
this.hubConnection.start().catch(err => console.error(err.toString()));
this.hubConnection.on('notify', (data: any) => {
this.messages.next(data);
});
});
}
send(message: string): Observable<void> {
let requestUrl = `${this._baseUrl}message`;
return this._http.post(requestUrl, message).pipe(map((result: any) => { }));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment