Created
May 23, 2018 08:33
-
-
Save GrillPhil/50f59a6e5b8dafbc88440a059cd9a5b6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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