Implementing Apollo Angular with GraphQL

What is GraphQL?

GraphQL is a query language created by Facebook. It allows us to describe the data in our API using a schema definition language. It uses a typed query system. We get exactly the data we ask for, and nothing more. It represents your API as a graph. Nodes are objects, and edges are the relationships between them.

Diagrammatic Representation of the Difference Between GraphQL & REST:

Prerequisites for Implementation of GraphQL in Angular:

  • Node.js and npm: For setting up a development environment.
  • GraphQL Server: Ensure you have a GraphQL server set up that your Angular application can query. This server can be built with various technologies such as Node.js, Python, Java, or others.
  • GraphQL Client Library: Choose a GraphQL client library for Angular. Popular options include Apollo Angular or GraphQL Request. These libraries provide utilities for querying GraphQL APIs and managing data.

Implementation:

1 . Set Up Angular Project: Create a new Angular project using Angular CLI

ng new my-graphql-app
cd my-graphql-app

2 . Install Dependencies: Install apollo-angular library with Angular Schematics

ng add apollo-angular

After hitting this command, you’ll be required to enter your GraphQL server’s URL. The countries API, a fantastic public endpoint for data about nations, continents, and languages, will be used in this example.

Visit trevorblades.com to see it.

? Url to your GraphQL API https://countries.trevorblades.com? Version of GraphQL 16
CREATE src/app/graphql.module.ts (670 bytes)
UPDATE package.json (1135 bytes)
UPDATE tsconfig.json (857 bytes)
UPDATE src/app/app.module.ts (462 bytes)
- Installing packages (npm)...

The aforementioned screenshot illustrates how the script generates a new module named graphql.module.ts and automatically updates all other files with the required imports and configurations.

This is how the graphql.module.ts file should appear:

import { APOLLO_OPTIONS, ApolloModule } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { NgModule } from '@angular/core';
import { ApolloClientOptions, InMemoryCache } from '@apollo/client/core';

const uri = ' https://countries.trevorblades.com'; // <-- add the URL of the GraphQL server here
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
return {
link: httpLink.create({ uri }),
cache: new InMemoryCache(),
};
}

@NgModule({
exports: [ApolloModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
},
],
})
export class GraphQLModule {}

3 . Create the Interface:

We will now make two basic interfaces: one for the continent and one for the country. Our data from the API will eventually be stored in these two objects.

import { Continent } from "./continent"

export interface Country {
name : string
capital : string
currency : string
emoji : string
phone : string
continent : Continent

}
export interface Continent {
name : string
}

4 . Create a New Countries Service:

The next step is to construct a CountriesService that all application classes can use to retrieve the nations once we’ve created our interfaces. Later on, we will inject it into the CountriesComponent constructor using the dependency injection that Angular provides.

With the CLI, you may create a new Angular service by running the command listed below:

ng g service countries

Now, open the generated countries.service.ts file and place the following code:

import { Injectable } from '@angular/core';
import { Apollo, gql } from 'apollo-angular';
import { Observable, map } from 'rxjs';
import { Country } from '../interface/country';

// write a GraphQL query that asks for information (name , capital, etc..) about all countries
const COUNTRIES = gql`
{
countries {
name
capital
currency
emoji
phone

continent {
name
}
}
}

`;

@Injectable({
providedIn: 'root'
})
export class CountriesService {
constructor(private apollo: Apollo) { }

getCountries(): Observable<Country[]> {
return this.apollo.watchQuery<any>({query: COUNTRIES,}).valueChanges.pipe(map((result) => result.data.countries));
}
}

The next step is to construct a CountriesService that all application classes can use to retrieve the nations once we’ve created our models. Later on, we will inject it into the CountriesComponent constructor using the dependency injection that Angular provides.

With the CLI, you may create a new Angular service by running the command listed below:

Related read: Angular Setup and CRUD Operations: A Comprehensive Guide

Transform Your Angular Application with GraphQL Using Apollo Angular

5 . Create a New Countries Component:

Now, let’s generate a new component using the below command:

ng g c countries

Add the selector to the app.component.html file:

<app-countries></app-countries>

Open the countries.component.ts file and paste the following code:

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { CountriesService } from '../../core/services/countries.service'

@Component({
selector: 'app-countries',
templateUrl: './countries.component.html',
styleUrls: ['./countries.component.scss']
})

export class CountriesComponent implements OnInit{
@ViewChild(MatPaginator) paginator: MatPaginator | any;
@ViewChild(MatSort) sort: MatSort | any;
displayedColumns: string[] = [
'name',
'capital',
'currency',
'emoji',
'phone',
'continent',
];

dataSource!: MatTableDataSource<any>;
constructor(private countriesService: CountriesService) {}
ngOnInit() {
this.countriesService.getCountries().subscribe(data => {
this.dataSource = new MatTableDataSource(data);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
});
}
}

🔸 displayedColumns: The names of the data table columns that will be shown.

🔸 dataSource$: The nations we previously retrieved from the server are included in the observable. The countriesService, which is injected into the component’s constructor, is where we are calling the getCountries() function.

6 . Add Angular Material:

We will be using Angular material’s data table component to display the data in this example.

Type the following command to add the library to your project:

ng add @angular/material

We need to import MatTableModule, MatPaginatorModule, and MatSortModule in app.module.ts.

7 . Display the Countries in the Datatable:

In the HTML file, place the following code:

<div class="style">GraphQL in Angular</div>

<div class="mat-elevation-z8 mt">
<table mat-table [dataSource]="dataSource" matSort>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
<td mat-cell *matCellDef="let row">{{ row.name }}</td>
</ng-container>

<!-- Capital Column -->
<ng-container matColumnDef="capital">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Capital</th>
<td mat-cell *matCellDef="let row">{{ row.capital }}</td>
</ng-container>

<!-- Currency Column -->
<ng-container matColumnDef="currency">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Currency</th>
<td mat-cell *matCellDef="let row">{{ row.currency }}</td>
</ng-container>

<!-- Emoji Column -->
<ng-container matColumnDef="emoji">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Emoji</th>
<td mat-cell *matCellDef="let row">{{ row.emoji }}</td>
</ng-container>

<!-- Phone Column -->
<ng-container matColumnDef="phone">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Phone</th>
<td mat-cell *matCellDef="let row">+{{ row.phone }}</td>
</ng-container>

<!-- Continent Column -->
<ng-container matColumnDef="continent">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Continent</th>
<td mat-cell *matCellDef="let row">{{ row.continent.name }}</td>
</ng-container>

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
<mat-paginator
[pageSizeOptions]="[5, 10, 20]"
showFirstLastButtons
aria-label="Select page of periodic elements"
>
</mat-paginator>
</div>

Result:

Results-of-Datatable
Fig: Results of Datatable
coma

Conclusion

We learned how to rapidly set up GraphQL in an Angular application with this easy tutorial. When installing and configuring dependencies, the Angular diagrams save time when compared to doing it all yourself. By embracing GraphQL and leveraging tools like Apollo Angular, we’ve streamlined our development process and enhanced our application’s capabilities.

As we conclude, let’s continue exploring GraphQL’s potential to optimize data retrieval and management, ensuring our Angular applications remain efficient and scalable.

 

Keep Reading

Keep Reading

Launch Faster with Low Cost: Master GTM with Pre-built Solutions in Our Webinar!

Register Today!
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?