ngx-signalr-hubservice
Version:
Makes using signalr in angular 2 easy
89 lines (74 loc) • 2.45 kB
Markdown
# Example chat application
Here's an example chat application. Make sure you add the HubService to your app module's providers.
```typescript
import { Component, OnInit, NgZone } from '@angular/core';
import {
HubService,
Hub,
HubSubscription,
HubWrapper
} from 'ngx-signalr-hubservice';
import 'rxjs/add/operator/toPromise';
const url = 'http://localhost:64339/signalr';
export class AppComponent implements OnInit {
private hubWrapper: HubWrapper;
connecting = false;
connected = false;
sending = false;
enteredName = false;
name = '';
message = '';
messages = <[ { name: string, message: string } ]> [];
constructor(private hubService: HubService, private ngZone: NgZone) {
this.hubWrapper = hubService.register(this);
}
async ngOnInit() {
this.connecting = true;
this.connected = await this.hubService.connect({ url: url }).toPromise();
this.connecting = false;
}
async sendMessage() {
this.sending = true;
await this.hubWrapper.invoke("sendMessage", this.name, this.message).toPromise();
this.message = '';
this.sending = false;
}
receiveMessage(name: string, message: string) {
//run inside zone to update UI
this.ngZone.run(() => {
this.messages.push({ name: name, message: message });
});
}
}
```