How to Use GraphQL with Angular

In this tutorial, we will learn how to use GraphQL with Angular. Angular is a popular framework for building web applications, and GraphQL is a query language and runtime for APIs. By combining these technologies, we can create efficient and flexible APIs that allow clients to request exactly the data they need.

Prerequisites

Before we begin, make sure you have the following installed on your system:

  • Node.js (v10 or higher)
  • Angular CLI (v11 or higher)
  • GraphQL server (we will use Apollo Server for this tutorial)

You can install Node.js from the official website (https://nodejs.org), and then install Angular CLI globally by running the following command in your terminal:

npm install -g @angular/cli

To set up the GraphQL server, we will use Apollo Server. Apollo Server is an open-source GraphQL server that works with any GraphQL schema. You can install it by running the following command:

npm install apollo-server graphql

Setting up the GraphQL Server

Before we start working with Angular, let’s set up our GraphQL server using Apollo Server. Create a new folder for your project and navigate to it in your terminal. Then, run the following command to initialize a new Node.js project:

npm init -y

Next, create a file named server.js and open it in your favorite code editor. In this file, we will set up our GraphQL server using Apollo Server.

First, import the necessary modules:

const { ApolloServer, gql } = require('apollo-server');

Next, define your GraphQL schema. This schema describes the available queries and types in your API. In this example, we will create a simple schema with a greeting query that returns a string:

const typeDefs = gql`
  type Query {
    greeting: String
  }
`;

Then, define the resolver functions for your schema. These functions define how to fetch the data for each query. In this case, we will return a static string for the greeting query:

const resolvers = {
  Query: {
    greeting: () => 'Hello, world!',
  },
};

Now, create an instance of ApolloServer and pass in your schema and resolvers:

const server = new ApolloServer({ typeDefs, resolvers });

Finally, start the server by calling the listen method:

server.listen().then(({ url }) => {
  console.log(`Server running at ${url}`);
});

Your server.js file should now look like this:

const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type Query {
    greeting: String
  }
`;

const resolvers = {
  Query: {
    greeting: () => 'Hello, world!',
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server running at ${url}`);
});

Save the file and run the following command in your terminal to start the GraphQL server:

node server

You should see a message indicating that the server is running at a specific URL (e.g., `http://localhost:4000`). Keep this URL handy as we will need it later.

Creating an Angular Project

Now that our GraphQL server is up and running, let’s create a new Angular project to consume the API.

Open a new terminal window, navigate to the desired directory, and run the following command to generate a new Angular project:

ng new angular-graphql-demo

Follow the prompts to customize your project, and then navigate to the project directory:

cd angular-graphql-demo

Installing Required Dependencies

Next, we need to install some dependencies to work with GraphQL in Angular. First, install the Apollo Angular package, which provides integration for Apollo Client with Angular:

npm install @apollo/client graphql

This package includes both the Apollo Client library and the GraphQL query language package.

Configuring Apollo Client

To use Apollo Client in our Angular project, we need to configure it with the URL of our GraphQL server.

Open src/app/app.module.ts in your code editor, and import the required modules:

import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
import { ApolloModule } from 'apollo-angular';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

Then, create an Apollo Client instance with the URL of your GraphQL server:

const uri = 'http://localhost:4000'; // Replace this with your server URL

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    ApolloModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {
  constructor(apollo: ApolloClient<unknown>) {
    apollo
      .create({
        link: new HttpLink({ uri }),
        cache: new InMemoryCache(),
      });
  }
}

Next, remove the default AppComponent from the app.component.ts file and replace it with a new component for our GraphQL demo.

Building the GraphQL Component

Create a new file named graphql.component.ts in the src/app directory, and add the following code to define your component:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-graphql',
  template: `
    <div>
      <h2>Greeting</h2>
      {{ greeting }}
    </div>
  `,
})
export class GraphqlComponent implements OnInit {
  greeting: string;

  constructor() {}

  ngOnInit() {}
}

This component simply displays the result of the greeting query we defined earlier.

Generating GraphQL Code

To consume the GraphQL server, we need to generate TypeScript types for our queries and mutations.

Open your terminal, navigate to the Angular project root directory, and run the following command:

ng generate apollo:components

This command generates a graphql.ts file in the src/app directory.

Writing GraphQL Queries

Open the graphql.ts file in your code editor and modify it as follows:

import { gql } from 'apollo-angular';

export const GREETING_QUERY = gql`
  query GetGreeting {
    greeting
  }
`;

Here, we define our GraphQL query using the gql template tag provided by the apollo-angular package. The GetGreeting query requests the greeting field from the server.

Consuming the GraphQL API

Open src/app/graphql.component.ts in your code editor and update the code as follows:

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

@Component({
  selector: 'app-graphql',
  template: `
    <div>
      <h2>Greeting</h2>
      {{ greeting }}
    </div>
  `,
})
export class GraphqlComponent implements OnInit {
  greeting: string;

  constructor(private apollo: Apollo) {}

  ngOnInit() {
    this.apollo
      .watchQuery<any>({
        query: GREETING_QUERY,
      })
      .valueChanges.subscribe(({ data }) => {
        this.greeting = data.greeting;
      });
  }
}

In this code, we import the Apollo service from apollo-angular and the GREETING_QUERY we defined earlier. In the ngOnInit method, we use the watchQuery method to execute the GREETING_QUERY and subscribe to the result. When the query completes, we update the greeting property with the returned value.

Updating the App Component

Open src/app/app.component.ts in your code editor and update the code as follows:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <app-graphql></app-graphql>
  `,
})
export class AppComponent {}

We simply remove the default content and add our app-graphql component.

Updating the App Module

Open src/app/app.module.ts in your code editor and update the imports as follows:

import { HttpClientModule } from '@angular/common/http';

Then, add the HttpClientModule to the imports array:

imports: [
  BrowserModule,
  ApolloModule,
  HttpClientModule,
],

This module enables the Apollo service to make HTTP requests.

Running the Application

Now that we have configured everything, let’s start the Angular development server and see the results.

In your terminal, navigate to the project directory and run the following command to start the Angular development server:

ng serve

Open your browser and navigate to `http://localhost:4200`. You should see the greeting message from the server rendered in the browser.

Congratulations! You have successfully built an Angular application that consumes a GraphQL API.

Conclusion

In this tutorial, we learned how to use GraphQL with Angular. We created a GraphQL server using Apollo Server, configured an Angular application to consume the server, generated TypeScript types for our queries, and consumed the GraphQL API using Apollo Client. By combining Angular and GraphQL, you can build efficient and flexible APIs that meet the specific data needs of your clients.

Related Post