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

Angular Components with GraphQL Queries

Use a GraphQL query to populate a list of messages in an Angular component

We have already set up Apollo Angular so that we can talk to the Apollo GraphQL API. Now we will use it to retrieve a message list with a GraphQL query.

Describe the data we need

Open a command-line prompt or terminal if you haven't already. We will need to create a few files to hold our GraphQL operations, our data service and some shared utilities. Run the following commands.

  • cd <project-folder>/web-app/src/app
  • mkdir -p ./shared
  • touch ./messages/messages.operations.ts
  • touch ./shared/utils.ts
  • ng generate service messages/messages-data

The following files should be added:

|--app
|  |--messages
|  |  |--messages.operations.ts
|  |  |--messages-data.ts
|  |--shared
|  |  |--utils.ts

Note: Depending on your version of the Angular CLI, the generated service file may be named messages-data.ts or messages-data.service.ts. This tutorial uses messages-data.ts.

We will start by describing the shape of the data that we expect back from our GraphQL API as TypeScript interfaces, so that our code is type-checked. Open the file messages/message.model.ts that we created earlier and add the following interfaces below the existing MessageView interface:

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

/**
 * Shapes of the selection sets in `messages.operations.ts`.
 */
export interface ConversationUser {
  __typename: 'User';
  id: string | null;
  name: string | null;
  colour: string | null;
  avatarUrl: string | null;
}

export interface ConversationMessage {
  __typename: 'Message';
  id: string | null;
  text: string | null;
  fromYou: boolean | null;
  timestamp: string | null;
  user: ConversationUser | null;
}

export interface GetMessagesData {
  messages: Array<ConversationMessage | null> | null;
}

export interface GetMessagesVariables {
  max: number;
}

Notice that most properties can be null. This mirrors our GraphQL schema, where we haven't marked any field as required. The __typename property is added to every object by Apollo Client so it can identify each type in its cache.

We will create our query using Fragments in the shape of the GraphQL data that we require in the response.

GraphQL Fragments

Fragments are an excellent way of grouping common properties used for different user interface views of the same data models.

We will create a fragment for viewing a message and also a user within our view-conversation.ts component. Open the file messages.operations.ts and add the following code, starting with the user:

File path icon web-app/src/app/messages/messages.operations.ts
import { gql } from 'apollo-angular';

export const CONVERSATION_USER_FRAGMENT = gql`
  fragment ConversationUser on User {
    id
    name
    colour
    avatarUrl
  }
`;

You may have noticed that the properties resemble the User object that we created for our GraphQL API. The syntax fragment ConversationUser on User defines a fragment called ConversationUser that will define properties from the User model of our GraphQL API. The gql function is a template literal tag that parses our GraphQL string into a document that Apollo can send.

If you have a compatible IDE (such as JetBrains Webstorm), there may be a plugin available similar to JS GraphQL for Webstorm. The plugin gives you GraphQL Schema introspection, which allows external services to map the data models defined in a schema and can add an extra level of error-catching and debugging when describing properties and models used from the API.

Next, in the same file, add a fragment for a message:

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

export const CONVERSATION_MESSAGE_FRAGMENT = gql`
  fragment ConversationMessage on Message {
    id
    text
    fromYou
    timestamp
    user {
      ...ConversationUser
    }
  }
  ${CONVERSATION_USER_FRAGMENT}
`;

Here we've created a fragment to represent the data we need on a Message model for our view-conversation.ts file. We've also mixed-in the ConversationUser fragment into the user property of our Message fragment and maintain a clean level of separation. In order to use the ConversationUser fragment, we have to include it within our gql template literal using the template literal expression ${CONVERSATION_USER_FRAGMENT}.

Now we have all the fragments of our GraphQL request, lets use them to build a query.

GraphQL Client Queries

Still in messages.operations.ts, add the following imports at the top of the file and the query at the bottom:

File path icon web-app/src/app/messages/messages.operations.ts
import { gql } from 'apollo-angular';

import { GetMessagesData, GetMessagesVariables } from './message.model'; // <-- Add new import

export const MESSAGES_MAX = 4;

// Existing fragments...

export const GET_MESSAGES = gql<GetMessagesData, GetMessagesVariables>`
  query GetMessages($max: Int) {
    messages(max: $max) {
      ...ConversationMessage
    }
  }
  ${CONVERSATION_MESSAGE_FRAGMENT}
`;

In our GET_MESSAGES operation we've written our top-level query for retrieving a list of messages and again used fragments to define the messages shape. The two type arguments given to gql (<GetMessagesData, GetMessagesVariables>) let Apollo and TypeScript know the shape of the response and shape of the variables, so we get type-checking and autocomplete on the result.

We can restrict the amount of messages returned from this query by using the $max variable. We will pass it the value of the MESSAGES_MAX constant, which limits the conversation to the latest 4 messages.

Create an Angular Service to retrieve messages

Now we will create a service that wraps Apollo and gives our components a simple way to ask for data. Open the file messages/messages-data.ts and replace the contents with the following code:

File path icon web-app/src/app/messages/messages-data.ts
import { Injectable, inject } from '@angular/core';
import { Apollo } from 'apollo-angular';

import { GET_MESSAGES, MESSAGES_MAX } from './messages.operations';

@Injectable({ providedIn: 'root' })
export class MessagesData {
  private readonly apollo = inject(Apollo);

  watchMessages() {
    return this.apollo.watchQuery({
      query: GET_MESSAGES,
      variables: { max: MESSAGES_MAX },
    });
  }
}

The @Injectable syntax lets Angular know that this is a service to be injected into components and other services. Injectors can be defined as application-wide singleton instances by specifying the providedIn: 'root' property and value.

We use Angular's inject() function to get an instance of the Apollo service that we configured when setting up our application.

The watchQuery method sends our query to the GraphQL API and then keeps watching the result in Apollo's cache. Whenever the cached data changes, for example when a new message is added later in this tutorial, the query emits an updated result automatically. This is what will make our message list update live. The valueChanges property of what it returns is an observable of these results.

Use the service to display messages from the GraphQL endpoint

Open the file messages/view-conversation/view-conversation.ts. Lets remove the hard-coded data that we left in this file. Remove the messages property of the ViewConversation component from ViewConversation.

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
export class ViewConversation {
  protected readonly messages = signal<MessageView[]>([
    // Remove the code below
    {
      id: '1',
      sent: new Date(),
      text: 'This message is bound to component data',
      user: {
        name: 'Shane Edwards',
        avatarUrl: 'https://lh3.googleusercontent.com/a-/AAuE7mAuiepkKGsj-1L9lhHSHtnQsXlVqHEQfJqzOoGz=s96-cc-rg',
        colour: '0080a2'
      },
      fromYou: false
    },
    {
      id: '2',
      sent: new Date(),
      text: 'Cool',
      user: {
        name: 'You',
        avatarUrl: 'https://avatars.githubusercontent.com/u/5592738?v=4',
        colour: 'c16fe0'
      },
      fromYou: true
    }
    // Stop here
  ]);
}

We will replace this signal with one that is calculated from the GraphQL result. We first need a small utility function, which we'll put in the shared utilities file. Open shared/utils.ts and add the following:

File path icon web-app/src/app/shared/utils.ts
export function isPresent<T>(value: T | null | undefined): value is T {
  return value !== null && value !== undefined;
}

The GraphQL result can contain null items. This function filters them out, and the value is T return type tells TypeScript that anything which passes the filter is definitely not null.

Now open view-conversation.ts again. We need to add some imports at the top of the file, as well as a function that will create MessageView instances from ConversationMessage data. This creates an object that our Angular template can bind to, and should be defined after the imports.

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'; // <-- Change imports
import { toSignal } from '@angular/core/rxjs-interop'; // <-- Add new import

import { isPresent } from '../../shared/utils'; // <-- Add new import
import { ConversationMessage, MessageView } from '../message.model'; // <-- Add ConversationMessage
import { MessagesData } from '../messages-data'; // <-- Add new import

const DEFAULT_COLOUR = 'dca629';
const DEFAULT_AVATAR_URL = 'assets/avatar.png';

function toMessageView(message: ConversationMessage): MessageView {
  return {
    id: message.id ?? '',
    sent: new Date(parseInt(message.timestamp ?? '0', 10) * 1000),
    text: message.text ?? '',
    fromYou: message.fromYou ?? false,
    user: {
      name: message.user?.name ?? '',
      colour: message.user?.colour || DEFAULT_COLOUR,
      avatarUrl: message.user?.avatarUrl || DEFAULT_AVATAR_URL,
    },
  };
}

// Existing code...

This function essentially transforms an object from a ConversationMessage type to a MessageView type. It converts the Slack timestamp (in seconds) to a JavaScript Date, and uses nullish coalescing (??) to supply a default value wherever the API sent null.

Message views created by the function above use the same static image if the user doesn't have an image associated with their account and also anonymous users. Here, you can save and add the image below to your web-app/public folder (create the assets folder if it doesn't exist) or add your own if you wish.

Avatar

Next we will get an instance of our new service into the component, call it, and convert the result into a signal. Replace the ViewConversation class with the following:

File path icon web-app/src/app/messages/view-conversation/view-conversation.ts
// Existing code...

@Component({
  selector: 'app-view-conversation',
  imports: [DatePipe],
  templateUrl: './view-conversation.html',
  styleUrl: './view-conversation.scss',
})
export class ViewConversation {
  private readonly messagesData = inject(MessagesData);

  private readonly messagesResult = toSignal(this.messagesData.watchMessages().valueChanges);

  protected readonly loadError = computed(() => this.messagesResult()?.error);

  protected readonly messagesLoaded = computed(() => this.messagesResult()?.dataState === 'complete');

  protected readonly messages = computed(() => {
    const result = this.messagesResult();

    if (result?.dataState !== 'complete') {
      return [];
    }

    return (result.data.messages ?? [])
      .filter(isPresent)
      .map(toMessageView)
      .reverse();
  });
}

There are a few new things here. toSignal subscribes to the valueChanges observable for us and exposes its latest value as a signal, cleaning up the subscription automatically when the component is destroyed. That means we no longer need to write a subscribe call or an ngOnInit method.

The messages signal is now a computed signal. A computed signal works out its value from other signals and recalculates whenever they change. Here it is derived from messagesResult, so each time Apollo emits a new result our list of messages updates, and so does the template.

Apollo reports whether a result is ready through its dataState property. We only map messages once the state is 'complete', and until then we show an empty list. If data is complete, we filter out any null messages, map each item to a MessageView with our function (toMessageView) and reverse the list. The API returns the newest message first but a conversation reads best with the newest message at the bottom.

We also added two small signals, loadError and messagesLoaded, that lets our template show a message if loading fails or if the conversation is empty. Open messages/view-conversation/view-conversation.html and add the following code at the top of the messages-view-conversation block, and change the @for block to read from our new signal (the @for already calls messages(), so it needs no change):

File path icon web-app/src/app/messages/view-conversation/view-conversation.html
<div class="messages-view-conversation">
  <!-- Add the new @if blocks below -->
  @if (loadError()) {
    <p class="messages-view-conversation__error" role="alert">Messages could not be loaded.</p>
  } @else if (messagesLoaded() && !messages().length) {
    <h1 class="messages-view-conversation__heading">Write a message</h1>
  }

  <div class="messages-view-conversation__list">
    <!-- Existing code... -->
  </div>
</div>

The @if block show an error message if loading failed, otherwise show a heading inviting the user to write a message when the conversation has loaded but is empty.

Testing our feature

At the moment we don't have messages in our service to test if our feature is working with the GraphQL endpoint, lets fix that.

We can't create a message from our application because we haven't built this feature just yet. But we can send messages from Slack's own applications to test our new user interface with real GraphQL data.

If you haven't already, download and install the Slack app to your computer, you will need to log in to your Slack workspace. Use your workspace URL (created when creating the authentication tokens from the setup guide, the details should be in your inbox) along with your email address and password to sign in to the Slack app.

You might recall that in our web-api we hard-coded a constant called channelName in our messages.messages.query.js resolver file. This holds the value conversation-1 and will be the Slack channel name that gets created before the first message is sent by a user.

Once logged in to your Slack workspace, you should see a heading in the left hand navigation called Channels and a '+' sign next to it. Click this to create a new channel and name it conversation-1, make sure this isn't a private channel.

After creating the new channel, type and send a new message in it. If you go back to your application and refresh the page, you should see the message you typed in our Angular application. We'll look at setting up the UI to receive create and receive real time messages in remaining parts of this tutorial.