I recently wrote an article demonstrating one way to integrate Angular 2 and SignalR using the channel / event model:
https://blog.sstorie.com/integrating-angular-2-and-signalr-part-2-of-2/
I donβt think that just linking to another site is considered appropriate, so here is the core of the Angular 2 service that provides SignalR:
import {Injectable, Inject} from "angular2/core"; import Rx from "rxjs/Rx"; export class SignalrWindow extends Window { $: any; } export enum ConnectionState { Connecting = 1, Connected = 2, Reconnecting = 3, Disconnected = 4 } export class ChannelConfig { url: string; hubName: string; channel: string; } export class ChannelEvent { Name: string; ChannelName: string; Timestamp: Date; Data: any; Json: string; constructor() { this.Timestamp = new Date(); } } class ChannelSubject { channel: string; subject: Rx.Subject<ChannelEvent>; } @Injectable() export class ChannelService { starting$: Rx.Observable<any>; connectionState$: Rx.Observable<ConnectionState>; error$: Rx.Observable<string>;
Then the component can use this service by subscribing (not in the sense of rxjs ...) to a specific channel and reacting to certain events:
import {Component, OnInit, Input} from "angular2/core"; import {Http, Response} from "angular2/http"; import Rx from "rxjs/Rx"; import {ChannelService, ChannelEvent} from "./services/channel.service"; class StatusEvent { State: string; PercentComplete: number; } @Component({ selector: 'task', template: ` <div> <h4>Task component bound to '{{eventName}}'</h4> </div> <div class="commands"> <textarea class="console" cols="50" rows="15" disabled [value]="messages"></textarea> <div class="commands__input"> <button (click)="callApi()">Call API</button> </div> </div> ` }) export class TaskComponent implements OnInit { @Input() eventName: string; @Input() apiUrl: string; messages = ""; private channel = "tasks"; constructor( private http: Http, private channelService: ChannelService ) { } ngOnInit() {
I tried to map SignalR concepts to observables, but I'm still learning how to use RxJS effectively. In any case, I hope this helps show how this can work in the context of an Angular 2 application.
Sam storie
source share