Subscriptions
Prerequisites
This article also assumes that you've already set up your environment as per getting started guide.
This article also assumes that you've followed HTTP + Subscriptions guide.
Overview
subscribe
is the primary method for subscribing to GraphQL back-end data in Apollo Orbit.
For a full documentation of subscriptions, please refer to the Apollo Client docs
subscribe
subscribe<TData, TVariables>(options: SubscriptionOptions<TVariables, TData>): Observable<SubscriptionResult<TData>>
Returns a SubscriptionResult<TData, TVariables>
observable. This observable is long lasting and continues to deliver results from GraphQL backend until unsubscribed to.
Executing a subscription
To execute a subscription, inject Apollo
and pass it a GraphQL subscription document.
Let's look at an example.
First, we'll create a GraphQL subscription named NewAuthor
:
fragment AuthorFragment on Author {
id
name
age
}
subscription NewAuthor {
newAuthor {
...AuthorFragment
}
}
Saving author.graphql will trigger codegen of NewAuthorSubscription
class in /graphql/types.ts file as per our setup.
For more information about codegen and how it works, please refer to the Codegen section.
Next, we define the subscription in our component:
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Apollo, mapSubscription } from '@apollo-orbit/angular';
import { NewAuthorSubscription } from '../graphql/types';
@Component({
selector: 'app-authors',
templateUrl: './authors.component.html',
styleUrls: ['./authors.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AuthorsComponent {
protected readonly newAuthorName$: Observable<string> = this.apollo.subscribe(new NewAuthorSubscription()).pipe(
mapSubscription(data => data.newAuthor.name)
);
public constructor(
private readonly apollo: Apollo
) { }
}
Then, we subscribe to the data using async
pipe:
@if (newAuthorName$ | async; as newAuthorName) {
<div class="alert-info">New author was added: {{ newAuthorName }}</div>
}
mapSubscription
Apollo Orbit provides a mapSubscription
RxJS operator to map data
of a subscription result while preserving the other properties.
This is useful when you want to map the subscription result without dealing with the nullability of data
property.
import { mapSubscription } from '@apollo-orbit/angular';
...
protected readonly newAuthorName$: Observable<string> = this.apollo.subscribe(new NewAuthorSubscription()).pipe(
mapSubscription(data => data.newAuthor.name)
);