import { Injectable } from '@angular/core' ; import { HubConnection , HubConnectionBuilder , LogLevel } from '@aspnet/signalr' ; import { Observable , Observer } from 'rxjs' ; import { environment } from '../../../environments/environment' ; import { FoodStoreFacade } from '../../food/store/food-store.facade' ; import { Ingredient } from '../../shared/models/ingredient.model' ; @ Injectable ( { providedIn : 'root' } ) export class SignalRService { private foodHubConnection : HubConnection ; constructor ( private facade ) { } initializeConnection ( ) { this . foodHubConnection = new HubConnectionBuilder ( ) . withUrl ( environment . server + 'foodhub' ) . configureLogging ( LogLevel . Information ) . build ( ) ; this . registerOnServerEvents ( ) ; return Observable . create ( ( observer ) => { this . foodHubConnection . start ( ) . then ( ( ) => { console . log ( 'Hub connection started' ) ; observer . next ( true ) ; observer . complete ( ) ; } ) . catch ( err => { console . log ( 'Error while establishing connection' , err ) ; observer . error ( err ) ; } ) ; } ) ; } private registerOnServerEvents ( ) { this . foodHubConnection . on ( 'food-added' , ( data ) => { this . facade . receivedFoodData ( data ) ; } ) ; this . foodHubConnection . on ( 'food-deleted' , ( data ) => { this . facade . receivedFoodDeleted ( data ) ; } ) ; this . foodHubConnection . on ( 'food-updated' , ( data ) => { this . facade . receivedFoodUpdated ( data ) ; } ) ; this . foodHubConnection . on ( 'ingredient-added' , ( foodId , ingredient ) => { this . facade . receivedIngredientAdded ( ingredient ) ; } ) ; this . foodHubConnection . on ( 'ingredient-deleted' , ( foodId , ingredientId ) => { this . facade . receivedIngredientDeleted ( ingredientId ) ; } ) ; } }