LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • 0001 to 0023
      • 0088 to 0723
      • 0901 to 0908
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Prerequisites
  • Setting Up the SignalR Server
  • Installing the SignalR Client Library
  • Creating the SignalR Service in Aurelia 2
  • Using the SignalR Service in an Aurelia 2 Component
  • Conclusion

Was this helpful?

Export as PDF
  1. Developer Guides
  2. Recipes

SignalR integration

SignalR is a library that enables real-time web functionality in your applications. This guide will show you how to integrate SignalR with an Aurelia 2 application to create interactive, real-time features.

Prerequisites

  • An existing Aurelia 2 project (you can create one using npx makes aurelia)

  • .NET Core SDK installed if you're setting up a SignalR server

  • SignalR client library installed in your Aurelia project

Setting Up the SignalR Server

If you don't have a SignalR server, create a new hub in your ASP.NET Core project:

using Microsoft.AspNetCore.SignalR;

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

Register the SignalR service and map the hub in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ... other configurations ...

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<ChatHub>("/chatHub");
    });
}

Installing the SignalR Client Library

Install the SignalR client package:

npm install @microsoft/signalr

or

yarn add @microsoft/signalr

Creating the SignalR Service in Aurelia 2

Define an interface for the SignalR service using the DI.createInterface function:

// src/signalr-service.ts
import { DI } from '@aurelia/kernel';
import * as signalR from '@microsoft/signalr';

export const ISignalRService = DI.createInterface<ISignalRService>('ISignalRService', x => x.singleton(SignalRService));

export interface ISignalRService {
  start(): Promise<void>;
  stop(): Promise<void>;
  sendMessage(user: string, message: string): Promise<void>;
}

export class SignalRService implements ISignalRService {
  private connection: signalR.HubConnection;

  constructor() {
    this.connection = new signalR.HubConnectionBuilder()
      .withUrl('YOUR_SERVER/chatHub')
      .configureLogging(signalR.LogLevel.Information)
      .build();

    this.connection.onclose(async () => {
      await this.start();
    });
  }

  async start(): Promise<void> {
    try {
      await this.connection.start();
      console.log('SignalR Connected.');
    } catch (err) {
      console.error('SignalR Connection failed: ', err);
      setTimeout(() => this.start(), 5000);
    }
  }

  async stop(): Promise<void> {
    await this.connection.stop();
    console.log('SignalR Disconnected.');
  }

  async sendMessage(user: string, message: string): Promise<void> {
    await this.connection.invoke('SendMessage', user, message);
  }
}

Using the SignalR Service in an Aurelia 2 Component

Inject the SignalR service into your Aurelia component and use it to send and receive messages:

// src/chat-component.ts
import { ISignalRService } from './signalr-service';
import { inject } from '@aurelia/kernel';

@inject(ISignalRService)
export class ChatComponent {
  public message: string = '';
  public messages: { user: string; message: string }[] = [];

  constructor(private signalR: ISignalRService) {
    this.signalR.connection.on('ReceiveMessage', (user: string, message: string) => {
      this.messages.push({ user, message });
    });
  }

  public bound(): void {
    this.signalR.start();
  }

  public unbound(): void {
    this.signalR.stop();
  }

  public sendMessage(): void {
    this.signalR.sendMessage('User1', this.message);
    this.message = '';
  }
}

And the corresponding HTML template:

<!-- src/chat-component.html -->
<template>
  <ul>
    <li repeat.for="msg of messages">${msg.user}: ${msg.message}</li>
  </ul>
  <input type="text" value.two-way="message" placeholder="Type a message...">
  <button click.trigger="sendMessage()">Send</button>
</template>

Conclusion

You have now successfully integrated SignalR with an Aurelia 2 application, enabling real-time communication between the server and clients. This example can be expanded to include more sophisticated real-time features, such as notifications, live updates, and collaborative environments.

Remember that managing the SignalR connection's lifecycle is crucial, especially in production environments, to ensure a stable and responsive user experience.

PreviousSecuring an appNextStrongly-typed templates

Last updated 1 year ago

Was this helpful?