Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Beginner’s Guide to GraphQL With Angular and Apollo

DZone 's Guide to

A Beginner’s Guide to GraphQL With Angular and Apollo

There's no denying GraphQL is the new hotness for API development. Let's get it working with Angular.

· Integration Zone ·
Free Resource

angular-lines-connecting

Let's build some connections.

GraphQL has been gaining popularity lately, to the point where it has made its way to the forefront of API development. There are several GraphQL clients available today for front-end frameworks. The Apollo client is one of the more popular ones for Angular applications.

In this article, we are going to build a small app using Angular and the Apollo client. In my last article, I talked about creating a GraphQL server with Spring Boot. We will use the same example for our Angular application.

Is React more your jam? Read On GraphQL and Building an Application Using React Apollo

Creating Our Angular App

Let’s create a new Angular project using the Angular CLI. Run the following command in a terminal or command prompt.

ng new angular-apollo –style=scss –routing=true


I have created a project with Angular 8 for this tutorial.

Once the project is created, navigate to the project directory angular-apollo in the command prompt or terminal. Add the apollo-angular dependency using the command below.

ng add apollo-angular


This command will add the following list of dependencies to the project.

"apollo-angular": "^1.6.0",
    "apollo-angular-link-http": "^1.6.0",
    "apollo-cache-inmemory": "^1.3.2",
    "apollo-client": "^2.6.0",
    "apollo-codegen": "^0.20.2",
    "apollo-link": "^1.2.11",
    "graphql": "^14.3.1",
    "graphql-tag": "^2.10.0"


This command will also create a new file called graphql.module.ts. This file can be found under/src/app/. In this file, you will find the following line.

const uri = ''; // <-- add the URL of the GraphQL server here


Add this URL http://localhost:8080/graphql to the line above. This is the GraphQL server endpoint that I created in my previous article.

Accessing GraphQL Mutation Endpoints in Angular Apollo

The GraphQL server contains the endpoints for creating and reading data for a Vehicle entity. The process that involves write operations is called Mutation. These operations may involve creates, updates, and deletes.

The vehicle data model on the server looks like:

type Vehicle {
    id: ID!,
    type: String,
    modelCode: String,
    brandName: String,
    launchDate: String
}


The mutation endpoint on the server is as follows.

type Mutation {
    createVehicle(type: String!, modelCode: String!, brandName: String, launchDate: String):Vehicle
}


Now, we will access this mutation endpoint using the Apollo client.

this.apollo.mutate({
      mutation: gql`mutation {
        createVehicle(type: "car", modelCode: "XYZ0192", brandName: "XYZ", launchDate: "2016-08-16") 
        {
          id
        }
      }`
    }).subscribe(data => {
      //successfully created vehicle entity.
    });


I have added the above code in app.component.ts as follows. This is just a basic example to show how the call is made using the Apollo client. Note that we could use services provided by the client for reusability and maintainability.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  data: any;

  constructor(private apollo: Apollo) { }

  ngOnInit() {
    this.apollo.mutate({
      mutation: gql`mutation {
        createVehicle(type: "car", modelCode: "XYZ0192", brandName: "XYZ", launchDate: "2016-08-16") 
        {
          id
        }
      }`
    }).subscribe(data => {
      //successfully created vehicle entity.
    });
  }
}


In this call, we can fetch all the fields from the Vehicle object or only a few fields that we need. Here, we are only asking for the id field. The server gives back only the id field in the data object.

Querying Data Using the Apollo Client

As the heading suggests, we will fetch the data using a GraphQL query. The query on the server is as follows:

type Query {
    vehicles(count: Int):[Vehicle]
    vehicle(id: ID):Vehicle
}


Using the Apollo client, we will access the above endpoint.

this.apollo.query({
      query: gql`query {
        vehicles(count: 1) 
        {
          modelCode,
          brandName
        }
      }`
    }).subscribe(({ data, loading }) => {
      this.data = data;
    });


Here, we are interested in only the modelCode and brandName fields. The server returns the data with only these fields.

Let’s add a little bit of HTML code to display the data.

<div class="card" *ngFor="let vehicle of data.vehicles">
    <label class="content">Model: {{ vehicle.modelCode }}</label>
    <label class="content">Brand: {{ vehicle.brandName }}</label>
</div>


Running the App

Run the application using ng serve. The final app looks like below.

Wrapping Up

We have just scratched the surface of the Apollo client — it offers many more features. Check out their documentation for further information.

I hope you enjoyed this article. Let me know if you have any comments or suggestions in the comment section below.

The example for this tutorial can be found on this GitHub repository.

Further Reading

Build a Health Tracking App With React, GraphQL, and User Authentication

Why We Advised Our Customer Against GraphQL

Topics:
integration ,graphql ,apollo ,angular 8 ,mutation ,typescript ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}