Part 9 from series: How to build a real-time chat app

Angular Components & GraphQL Subscriptions

Integrate GraphQL Subscriptions into Angular components to build a list of messages

Our subscription is ready in the GraphQL API. Lets now integrate our Angular components with the new subscription to get live message updates. We will check that our Apollo setup allows for websocket communication, add the subscription to our data service and finally use the subscription from an Angular component.

Configuring Apollo Client for use with Subscriptions

The Apollo client needs to allow websocket traffic and communication. To achieve this the link that handles the interaction with our API is split in to two parts. One branch of code will handle HTTP requests (queries and mutations) and another will handle websocket subscriptions.

If you followed the setup guide, you will already have this in place.

From your project folder, open the file web-app/src/app/core/apollo.ts and take a look at how the link is created inside the createServerLink function. The parts that are relevant to subscriptions are shown below. If your file doesn't match, update the relevant parts so that it does:

File path icon web-app/src/app/core/apollo.ts
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { getMainDefinition } from '@apollo/client/utilities';
import { Kind, OperationTypeNode } from 'graphql';
import { createClient } from 'graphql-ws';

// Existing code...

function createServerLink(httpLink: HttpLink): ApolloLink {
  const http = httpLink.create({
    // Existing code...
  });

  const ws = new GraphQLWsLink(
    createClient({
      url: `ws://${environment.graphQLRoot}/graphql`,
      connectionParams: { clientId },
      retryAttempts: Infinity,
      shouldRetry: () => true,
    }),
  );

  // Subscriptions go over the WebSocket, queries and mutations over HTTP
  return split(
    ({ query }) => {
      const definition = getMainDefinition(query);

      return (
        definition.kind === Kind.OPERATION_DEFINITION &&
        definition.operation === OperationTypeNode.SUBSCRIPTION
      );
    },
    ws,
    http,
  );
}

The GraphQLWsLink sends operations over a websocket connection. The retryAttempts and shouldRetry options tell the client to keep trying to reconnect if the connection is lost, for example if you restart your API.

The split function separates the requests made from the client by operation type. Its first argument is a test, which checks whether an operation is a subscription. Subscription requests are passed to the GraphQLWsLink (ws) and all other requests are passed to Apollo's HttpLink (http).

The InMemoryCache configured in apolloOptions will configure Apollo to save data (with caching enabled) in the memory of the browser tab. Our subscription will write new messages to this cache.

Describe the subscription

Just like our query and mutation, we first describe the subscription and the shape of its data. Open the file web-app/src/app/messages/message.model.ts and add the following interface at the bottom of the file:

File path icon web-app/src/app/messages/message.model.ts
// Existing code...

export interface OnMessageAddedData {
  messageAdded: ConversationMessage | null;
}

Then open web-app/src/app/messages/messages.operations.ts, import the new type and add the ON_MESSAGE_ADDED operation at the bottom of the file:

File path icon web-app/src/app/messages/messages.operations.ts
import {
  CreateMessageData,
  CreateMessageVariables,
  GetMessagesData,
  GetMessagesVariables,
  OnMessageAddedData, // <-- Add new import
} from './message.model';

// Existing code...

export const ON_MESSAGE_ADDED = gql<OnMessageAddedData, Record<string, never>>`
  subscription OnMessageAdded {
    messageAdded {
      ...ConversationMessage
    }
  }
  ${CONVERSATION_MESSAGE_FRAGMENT}
`;

We use the same ConversationMessage fragment, so messages that arrive from the subscription have exactly the same shape as the ones from our query. The Record<string, never> type tells TypeScript that this subscription takes no variables.

Subscribe to new messages in our data service

In our service, we will add a method that subscribes to new messages. Each time a message is received from the API, we add it to the cache that holds our message list. Open the file web-app/src/app/messages/messages-data.ts and add the following changes:

File path icon web-app/src/app/messages/messages-data.ts
import { Injectable, inject } from '@angular/core';
import { ApolloCache } from '@apollo/client';
import { Apollo } from 'apollo-angular';
import { Observable, filter, map, tap } from 'rxjs'; // <-- Add new import

import { isPresent } from '../shared/utils'; // <-- Add new import
import { ConversationMessage } from './message.model';
import {
  CREATE_MESSAGE,
  GET_MESSAGES,
  MESSAGES_MAX,
  ON_MESSAGE_ADDED, // <-- Add new import
} from './messages.operations';

@Injectable({ providedIn: 'root' })
export class MessagesData {
  // Existing code...

  watchMessages() {
    // Existing code...
  }

  /**
   * Emits each message pushed by the server, after it has been added to the cached conversation
   */
  messageAdded(): Observable<ConversationMessage> { // <-- Add new method
    return this.apollo.subscribe({ query: ON_MESSAGE_ADDED }).pipe(
      map((result) => result.data?.messageAdded),
      filter(isPresent),
      tap((message) => this.addMessage(message)),
    );
  }

  sendMessage(text: string) {
    // Existing code...
  }

  /**
   * Adds a message to the cached conversation without a server round trip
   */
  addMessage(message: ConversationMessage) { // <-- Add new method
    this.appendMessage(this.apollo.client.cache, message);
  }

  private appendMessage(cache: ApolloCache, message: ConversationMessage) {
    // Existing code...
  }
}

The subscribe method of Apollo gives us an observable that emits a result every time the server publishes a messageAdded event. We then use a few RxJS operators in pipe to process each result in turn:

  • map plucks the message out of the result.
  • filter(isPresent) discards the result if there was no message in it.
  • tap runs a side effect for each message. Here it calls addMessage, which uses the same appendMessage function that our mutation uses to add the message to the cache.

Remember that appendMessage ignores messages that are already in the cache. When you send a message from our app, it arrives twice: once as the response to the mutation and again from the subscription. That check makes sure it only appears once.

Updating the cache is all we need to do to update the user interface. Our ViewConversation component is watching the cached messages query, so as soon as a message is added, Angular receives the updated result and the template updates automatically. We don't need to write any code to update the messages list manually.

Subscribe to new messages from the component

The last thing to do is to start the subscription. Open the file web-app/src/app/messages/view-conversation/view-conversation.ts and make the following changes:

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
import { DatePipe } from '@angular/common';
import { Component, computed, inject } from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; // <-- Add takeUntilDestroyed

// Existing code...

export class ViewConversation { // Add <-- Add implementation
  // Existing code...

  protected readonly messages = computed(() => {
    // Existing code...
  });

  constructor() {
    this.messagesData.messageAdded().pipe(takeUntilDestroyed()).subscribe();
  }
}

In the constructor we call our new messageAdded method and subscribe to it. We don't need to do anything with the value that comes out, because the service has already added the message to the cache. Subscribing is what opens the websocket and starts listening for events.

takeUntilDestroyed automatically ends the subscription when the component is destroyed. Without it the subscription would stay open after the component had gone, which is a common cause of memory leaks. It can be used without any arguments here because we're in the constructor of the component.

We can also add a small changes to scroll the messages container for when a new message enters:

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
// Existing code...
import { Component, computed, inject, OnInit, afterRenderEffect, viewChild, ElementRef } from '@angular/core'; // <-- Add takeUntilDestroye
// Existing code...

export class ViewConversation implements OnInit {
  // Existing code...
  private readonly scrollTarget = viewChild.required<ElementRef<HTMLElement>>('scrollTarget');

  // Existing code...

  constructor() {
    afterRenderEffect(() => {
      this.messages();

      const el = this.scrollTarget().nativeElement;
      el.scrollTo({ top: el.scrollHeight });
    });
  }

  // Existing code...
}

And in the html add the scrollTarget id:

File path icon web-app/src/app/messages/view-conversation/view-conversation.html
<div class="messages-view-conversation" #scrollTarget>
    <!-- Existing code... -->
</div>

We should have everything we need to test our Angular subscription. Make sure your API is running (along with required environment variables from the setup guide and run your application with ng serve (if it's not already running).

Open your browser window and navigate to http://localhost:4200. If we type a new message and click send, or send a new message from a downloaded Slack app (in the channel conversation-1), the user interface should update instantly with your new message without the need for a page refresh.

We've done well to build functionality into our new feature. Our application could benefit a lot from focusing on a better user experience.