Using GraphQL with Angular

Kürşat Coşkun
5 min readDec 19, 2021

In this article, I will talk about how to use our services created with GraphQL in our Angular applications and how to exchange data more easily with these services through which dependencies. First of all, I would like to talk about the differences between GraphQL and REST services.

What is GraphQL?

GraphQL is an API standard developed by Facebook. GraphQL is an API query language that has been created by considering the size of the data going and coming over the web as mobile platforms become widespread, and its purpose is to specify the data that the client wants, and that allows the client to return this data. GraphQL has Schemas and Mutations. Schemas help us define the type of our data and then present it to the client via Query’s. Mutation, on the other hand, helps in operations such as adding, deleting and updating through queries, as the name suggests.

How is it different from REST services? Why should we use it?

While there is a robust methodology for building REST-based services, they are inherently inflexible.

REST services return a data as a result of the related endpoint call, graphQL is a query language, it can be called to return the desired objects of the desired data based on the related endpoint.

To give an example;
Let’s say we have a REST based service and call it with the api/users endpoint.

api/users

As a result of this call, the user list will return as follows.

[
{name: 'John', surName: 'Doe', age: 22}
{name: 'John', surName: 'Doe', age: 22},{name: 'John', surName: 'Doe', age: 22}
]

Now, let’s assume that we created this service with the same data on the graphQL side and call it as follows.

{
User {
name
}
}

If the above query is sent to the Apollo Client GraphQL server, it will output something like the following.

[{name: 'John'},{name: 'John'},{name: 'John'},
]

As we saw above, as a result of the query, the graphQL server will return us the objects of the relevant dataset that we requested in the query.

Using GraphQL Services with Angular

GraphQL query language can be used with many backend technologies and frameworks. However, when we look at it, the most preferred is node.js. Since the main topic here is to show how to use services on Angular, that is, how a client will consume services, I will proceed by using a GraphQL service that has already been released as open source.

The GraphQL service we will use here https://api.spacex.land/graphql/ will be a public service with information about SpaceX with documentation at this url.

Creating Angular Project and Apollo Angular Installation

First, we create a new angular application with the following command.

ng new graphql-angular-example

After creating our project, instead of adding dependencies for apollo angular one by one, we will add all apollo angular related configurations in our project with a single command line using Angular Schematics.

ng add apollo-angular

As you can see after this process is completed, graphql.module.ts is automatically added to the project and imported to this module into app.module.

Now we can add our graphql url to graphql.module.ts as follows.

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

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

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

After adding the GraphQL server url, let’s create our Angular service file. We will be able to query the data we want by the server by creating graphl queries in this file.

ng generate service rocket-information

After we create our service, we add a query to our service as follows. For the query, we need to import the gql from the apollo-angular package.

const ROCKET_INFORMATIONS = gql`
query Query($limit: Int!) {
launchesPast(limit: $limit) {
mission_name
launch_date_local
launch_site {
site_name_long
}
links {
article_link
video_link
}
rocket {
rocket_name
}
}
}
`;

Then let’s create a method that we can monitor this query, that is, we can present it as observable.

getRocketInformations(limit: number): Observable<any> {
return this.apollo.watchQuery<any>({
query: ROCKET_INFORMATIONS,
variables: {
limit: limit,
}
}).valueChanges;
}

The final version of our rocket-information.service.ts file should be as follows;

import { Injectable } from '@angular/core';
import {Apollo, gql } from 'apollo-angular';
import {Observable} from "rxjs";

const ROCKET_INFORMATIONS = gql`
query Query($limit: Int!) {
launchesPast(limit: $limit) {
mission_name
launch_date_local
launch_site {
site_name_long
}
links {
article_link
video_link
}
rocket {
rocket_name
}
}
}
`;

@Injectable({
providedIn: 'root'
})
export class RocketInformationService {

constructor(private apollo: Apollo) { }

getRocketInformations(limit: number): Observable<any> {
return this.apollo.watchQuery<any>({
query: ROCKET_INFORMATIONS,
variables: {
limit: limit,
}
}).valueChanges;
}
}

After completing all the requirements in our service, we will now call our service method on the component side and we will be able to use the data from the graphql server in our component.

We will create an observable variable in our app.component.ts file and assign the return value of the method in our service file to this observable.

import {Component, OnInit} from '@angular/core';
import {RocketInformationService} from "./rocket-information.service";
import {Observable} from "rxjs";

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

rocketInformations$!: Observable<any>;

constructor(private rocketService: RocketInformationService) {
}

ngOnInit() {
this.rocketInformations$ = this.rocketService.getRocketInformations(20);
}

}

After this stage, we will see the json version of the last 20 rocket launch information coming from the graphql server to the screen by using the async and json pipe of the observable between the pre tags in app.component.html.

<pre>{{rocketInformations$ |async |json}}</pre>

When we try to access localhost:4200 from the browser, a screen like the one below will appear.

As a result, applications developed using GraphQL in addition to REST services in our Angular applications are very popular, they are preferred because of their speed and incoming requests over the web, as they have smaller requests and responses in terms of data compared to REST-based architectures. In addition to these, Angular offers a very easy to use structure through dependencies such as apollo-angular.

--

--