DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Databases
  4. A Beginner’s Guide to GraphQL With Angular and Apollo

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.

Swathi Prasad user avatar by
Swathi Prasad
·
Sep. 03, 19 · Tutorial
Like (1)
Save
Tweet
Share
28.68K Views

Join the DZone community and get the full member experience.

Join For Free

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.

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



If you enjoyed this article and want to learn more about GraphQL, check out this collection of tutorials and articles on all things GraphQL.

GraphQL AngularJS

Published at DZone with permission of Swathi Prasad, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Demystifying the Infrastructure as Code Landscape
  • 10 Most Popular Frameworks for Building RESTful APIs
  • Introduction Garbage Collection Java
  • Using Swagger for Creating a PingFederate Admin API Java Wrapper

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: