Consuming GraphQL APIs in AngularJS

Loading

GraphQL is a query language for APIs and a runtime for executing queries by using a type system you define for your data. Unlike traditional REST APIs, GraphQL enables clients to request only the data they need and nothing more, reducing over-fetching and under-fetching of data. Integrating GraphQL with an AngularJS application can significantly improve the flexibility and efficiency of data fetching.

In this guide, we’ll walk through how to consume GraphQL APIs in AngularJS using a client like Apollo Client or using HTTP requests directly for simplicity.


1. Prerequisites

Before starting, ensure you have the following:
Basic knowledge of AngularJS
GraphQL API endpoint (For example, you can use GraphQL Placeholder)
AngularJS 1.x application set up


2. Setting Up Apollo Client in AngularJS

Apollo Client is one of the most popular libraries for interacting with GraphQL APIs. However, integrating it in AngularJS (especially versions prior to Angular 2+) requires a bit of extra setup.

A. Install Apollo Client

  1. You need to install Apollo Client and its dependencies. If you’re using npm or yarn, run the following command in your project directory: shCopyEditnpm install @apollo/client graphql
  2. After installation, ensure that Apollo Client can be used in your AngularJS app by linking the required scripts in your index.html:
  3. <script src="https://cdn.jsdelivr.net/npm/@apollo/client@3.5.0"></script> <script src="https://cdn.jsdelivr.net/npm/graphql@15.5.0"></script>

3. Apollo Client Configuration in AngularJS

A. Create Apollo Client Service

Create an ApolloService to manage communication between the AngularJS app and the GraphQL API.

angular.module('myApp').factory('ApolloService', function() {
const { ApolloClient, InMemoryCache, gql } = window['@apollo/client'];

const client = new ApolloClient({
uri: 'https://example-graphql-api.com/graphql', // Replace with your GraphQL endpoint
cache: new InMemoryCache()
});

return {
fetchData: function(query) {
return client.query({
query: gql`${query}`,
});
}
};
});

Here, the service makes the Apollo client available within your AngularJS app. It sends a GraphQL query using the client.query() method.


4. Creating a GraphQL Query in AngularJS

A. Define a Query

Now, let’s define a GraphQL query that will be sent to the API. Modify app.js or create a new controller to fetch the data.

angular.module('myApp', [])
.controller('GraphQLController', function ($scope, ApolloService) {
$scope.users = [];

// GraphQL query to get users
const GET_USERS_QUERY = `
query {
users {
id
name
email
}
}
`;

// Fetch data from GraphQL API
ApolloService.fetchData(GET_USERS_QUERY)
.then(function(response) {
$scope.users = response.data.users;
$scope.$apply(); // Trigger scope update
})
.catch(function(error) {
console.error("Error fetching data from GraphQL API:", error);
});
});

B. Bind the Data in the View

Now in index.html, you can display the fetched data.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GraphQL with AngularJS</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="myApp" ng-controller="GraphQLController">
<h2>User List from GraphQL API</h2>
<ul>
<li ng-repeat="user in users">
{{ user.name }} ({{ user.email }})
</li>
</ul>
</body>
</html>

In this example, the GET_USERS_QUERY fetches a list of users from the GraphQL endpoint. The users data is then bound to the view via AngularJS’s ng-repeat.


5. Sending Mutations with Apollo Client

GraphQL allows both queries (to fetch data) and mutations (to modify data). To send mutations, you can use the same Apollo service with slight changes.

A. Define a Mutation

Here’s an example of a mutation to add a user:

const ADD_USER_MUTATION = `
mutation AddUser($name: String!, $email: String!) {
addUser(name: $name, email: $email) {
id
name
email
}
}
`;

B. Use the Mutation in the Controller

In your AngularJS controller, you can define a function to call the mutation and pass in the variables.

angular.module('myApp').controller('GraphQLController', function ($scope, ApolloService) {
$scope.users = [];
$scope.newUser = { name: '', email: '' };

const GET_USERS_QUERY = `
query {
users {
id
name
email
}
}
`;

const ADD_USER_MUTATION = `
mutation AddUser($name: String!, $email: String!) {
addUser(name: $name, email: $email) {
id
name
email
}
}
`;

// Fetch Users
ApolloService.fetchData(GET_USERS_QUERY)
.then(function(response) {
$scope.users = response.data.users;
$scope.$apply();
});

// Add New User
$scope.addUser = function() {
if ($scope.newUser.name && $scope.newUser.email) {
ApolloService.fetchData(ADD_USER_MUTATION, {
name: $scope.newUser.name,
email: $scope.newUser.email
})
.then(function(response) {
$scope.users.push(response.data.addUser);
$scope.newUser = {}; // Reset form
$scope.$apply();
})
.catch(function(error) {
console.error("Error adding user:", error);
});
}
};
});

Now, when you call the addUser() method, it sends the ADD_USER_MUTATION to the server and adds a new user to the list.


6. Using HTTP Requests to Fetch GraphQL Data (Without Apollo)

If you don’t want to use Apollo Client and prefer direct HTTP requests, you can use AngularJS’s built-in $http service to send GraphQL queries and mutations.

A. Define GraphQL Request Using $http

angular.module('myApp', [])
.controller('GraphQLController', function ($scope, $http) {
const API_URL = 'https://example-graphql-api.com/graphql';
const GET_USERS_QUERY = `
query {
users {
id
name
email
}
}
`;

// Fetch data using $http
$http.post(API_URL, { query: GET_USERS_QUERY })
.then(function(response) {
$scope.users = response.data.data.users;
})
.catch(function(error) {
console.error("Error fetching data:", error);
});
});

This method is simpler but lacks the benefits of a dedicated client like Apollo (e.g., caching, pagination). However, it’s useful for small applications or when you don’t want to add extra dependencies.

Leave a Reply

Your email address will not be published. Required fields are marked *