// Tutorial //

How To Use The Apollo Client GraphQL with Angular 4+

Published on December 12, 2019
Default avatar
By kirill ibrahim
Developer and author at DigitalOcean.
How To Use The Apollo Client GraphQL with Angular 4+

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Apollo Client is the flexible, community-driven GraphQL client for Angular, JavaScript, and native platforms. It is designed from the ground up to make it easy to build UI components that fetch data with GraphQL. This article is a quick summary about how to use Apollo client GraphQL with your Angular 4+. Therefore you need to know about GraphQl and Angular 4+ before you read the following post.

Setup:

Install Angular CLI before you start by running the following command:

  1. ng add apollo-angular

One thing you need to set is the URL of your GraphQL Server, so open src/app/graphql.module.ts and set URI variables:

const uri = 'https://w5xlvm3vzz.lp.gql.zone/graphql'; //our test Graphql Server which returns rates

Queries:

We will use Apollo to attach GraphQL query results to our Angular UI elements, we will use Apollo.watchQuery method. We need to parse our query into a GraphQL document using the graphql-tag library. Apollo.watchQuery method expects one argument, an object with options, you can provide any available option in the same object. If your query takes variables, this is the place to pass them in:

const currentUser = gql`query currentUser($avatarSize: Int!) {
    currentUser {
      login
      avatar_url(avatarSize: $avatarSize)
    }
  }`;

@Component({template:`Login: {{currentUser?.profile}}`,})
class UserComponent implements OnInit, OnDestroy {
  currentUser: any;
  private querySubscription: Subscription;
  ngOnInit() {
    this.querySubscription = this.apollo.watchQuery({
      query: currentUser,
      variables: {
        avatarSize: 100,
      },
    }).valueChanges.subscribe(({data}) => {
      this.currentUser = data.currentUser;
    });
  }
  ngOnDestroy() {
    this.querySubscription.unsubscribe();
  }
}

Mutations:

Apollo handles GraphQL mutations. Mutations are identical to queries in syntax, the only difference being that you use the keyword mutation instead of query.

GraphQL mutations consist of two parts:

  1. The mutation name with arguments, which represents the actual operation to be done on the server.
  2. The fields you want back from the result of the mutation to update the client.

We will use the mutate method. We can pass options to mutate when we call it:

const submitRepository = gql`mutation submitRepository($repoFullName: String!) {
    submitRepository(repoFullName: $repoFullName) {
      createdAt
    }
  }`;

@Component({ ... })
class NewEntryComponent {
  constructor(private apollo: Apollo) {}

  newRepository() {
    this.apollo.mutate({
      mutation: submitRepository,
      variables: {
        repoFullName: 'graphql/angular'
      }
    }).subscribe(({ data }) => {
      console.log('got data', data);
    },(error) => {
      console.log('there was an error sending the query', error);
    });
  }
}

Optimistic Response:

Sometimes before the server responds with the result, we can predict the result of the mutation. For example, when a user comments on an article, we want to show the new comment in context immediately, without waiting on the latency of a round trip to the server, This is what we call Optimistic UI.

Apollo Client gives you a way to specify the optimisticResponse option, that will be used to update active queries immediately, in the same way that the server’s mutation response will. Once the actual mutation response returns, the optimistic part will be thrown away and replaced with the real result.

import { Component } from '@angular/core';
import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';

const submitComment = gql`mutation submitComment($repoFullName: String!, $commentContent: String!) {
    submitComment(repoFullName: $repoFullName, commentContent: $commentContent) {
      postedBy {
        login
        html_url
      }
      createdAt
      content
    }
  }`;

@Component({ ... })
class CommentPageComponent {
  currentUser: User;

  constructor(private apollo: Apollo) {}

  submit({ repoFullName, commentContent }) {
    this.apollo.mutate({
      mutation: submitComment,
      variables: { repoFullName, commentContent },
      optimisticResponse: {
        __typename: 'Mutation',
        submitComment: {
          __typename: 'Comment',
          postedBy: this.currentUser,
          createdAt: +new Date,
          content: commentContent,
        },
      },
    }).subscribe();
  }
}

Conclusion

In this article, we took a quick look at using Apollo Client GraphQL with Angular.


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?
Leave a comment