Tutorial

How To Use The Apollo Client GraphQL with Angular 4+

Published on December 12, 2019
author

kirill ibrahim

How To Use The Apollo Client GraphQL with Angular 4+

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
kirill ibrahim

author

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.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.