In modern web development, efficient data fetching is crucial for providing a smooth and responsive user experience. Traditional REST APIs can sometimes lead to over-fetching or under-fetching of data, causing unnecessary network calls or missing critical information. GraphQL, an API query language developed by Facebook, solves this problem by allowing clients to request exactly the data they need. In this guide, we’ll walk you through the steps of integrating Angular 19 with GraphQL for efficient data fetching, making your application more performant and responsive.
Step 1: Understanding GraphQL Basics
Before we dive into the integration process, let’s briefly discuss the basics of GraphQL:
Step 2: Setting Up the Angular Project
Let’s start by setting up a new Angular 19 project. If you already have an existing Angular project, you can skip this step.
Open your terminal and create a new Angular project:
ng new angular-graphql-app
Navigate to the newly created project folder:
cd angular-graphql-app
Serve the application:
ng serve
Your Angular app should now be running at http://localhost:4200
.
Step 3: Installing Required Dependencies
To integrate GraphQL with Angular, we need to install Apollo Client, a popular library for interacting with GraphQL APIs.
Install Apollo Client and the GraphQL package by running:
npm install apollo-angular apollo-angular-link-http graphql
Install Apollo Client’s in-memory cache to manage query data:
npm install @apollo/client
Step 4: Configuring Apollo Client in Angular
Now that we’ve installed the necessary dependencies, let’s configure Apollo Client in our Angular application.
Create a new file called graphql.module.ts
in the src/app
folder.
Set up Apollo Client and the HTTP link in this file:
import { NgModule } from '@angular/core';
import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpClientModule } from '@angular/common/http';
import { InMemoryCache } from '@apollo/client/core';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
@NgModule({
imports: [ApolloModule, HttpClientModule, HttpLinkModule],
exports: [ApolloModule],
})
export class GraphQLModule {
constructor(apollo: Apollo, httpLink: HttpLink) {
apollo.create({
link: httpLink.create({ uri: 'https://your-graphql-api-endpoint' }),
cache: new InMemoryCache(),
});
}
}
'https://your-graphql-api-endpoint'
with the actual URL of your GraphQL endpoint.InMemoryCache
is used to cache the data fetched by Apollo, reducing the number of network requests and improving performance.Step 5: Fetching Data with GraphQL Queries
Let’s now set up a component that will fetch data using a GraphQL query.
Create a new component, for example, users
, using Angular CLI:
ng generate component users
In the users.component.ts
file, import Apollo Client and define the GraphQL query to fetch users:
import { Component, OnInit } from '@angular/core';
import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';
const GET_USERS_QUERY = gql`
query GetUsers {
users {
id
name
email
}
}
`;
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css'],
})
export class UsersComponent implements OnInit {
users: any[] = [];
constructor(private apollo: Apollo) {}
ngOnInit() {
this.apollo
.watchQuery({
query: GET_USERS_QUERY,
})
.valueChanges.subscribe((result: any) => {
this.users = result?.data?.users;
});
}
}
In the template (users.component.html
), display the list of users:
<div *ngIf="users?.length; else noUsers">
<ul>
<li *ngFor="let user of users">
<p>{{ user.name }} - {{ user.email }}</p>
</li>
</ul>
</div>
<ng-template #noUsers>
<p>No users found</p>
</ng-template>
GET_USERS_QUERY
fetches a list of users with their id
, name
, and email
.apollo.watchQuery
method subscribes to the GraphQL query and updates the component’s state when the data is fetched.Step 6: Displaying Data in the App
Add the UsersComponent
to the app.component.html
to display the data in your application.
Open app.component.html
and add the following:
<app-users></app-users>
Run the Angular app:
ng serve
Now, you should see a list of users being fetched from the GraphQL API and displayed in your Angular app.
Step 7: Handling Errors and Loading States
To improve the user experience, it’s a good idea to handle loading and error states.
Modify the users.component.ts
to handle loading and error states:
export class UsersComponent implements OnInit {
users: any[] = [];
loading = true;
error: any;
constructor(private apollo: Apollo) {}
ngOnInit() {
this.apollo
.watchQuery({
query: GET_USERS_QUERY,
})
.valueChanges.subscribe(
(result: any) => {
this.users = result?.data?.users;
this.loading = false;
},
(error) => {
this.error = error;
this.loading = false;
}
);
}
}
Update the template to show loading and error messages:
<div *ngIf="loading">Loading...</div>
<div *ngIf="error">Error loading data</div>
<div *ngIf="users?.length; else noUsers">
<ul>
<li *ngFor="let user of users">
<p>{{ user.name }} - {{ user.email }}</p>
</li>
</ul>
</div>
<ng-template #noUsers>
<p>No users found</p>
</ng-template>
Conclusion
Integrating Angular 19 with GraphQL for data fetching provides a more efficient and flexible approach to managing API requests. GraphQL allows you to fetch only the data you need, reducing the amount of data transferred and improving the performance of your application. With the Apollo Client in Angular, you can seamlessly integrate GraphQL into your Angular app, enabling features like caching, real-time updates, and more.