Consuming Drupal APIs in Angular appsfor Drupal 8 , 9 , 10 , and 11

Last updated :  

In the progression of our Headless Drupal series, we now turn to integrating Angular applications with Drupal APIs. Angular, a platform developed by Google, is well-suited for building dynamic single-page applications (SPAs) that can efficiently interact with your Drupal backend.

Working with Drupal APIs in Angular

With Angular, you can easily consume Drupal's JSON:API or GraphQL endpoints to fetch and manage content. Angular is built with TypeScript, allowing for structured, manageable, and reliable code.

Step 1: Set Up an Angular Application

To get started, ensure you have Angular CLI installed on your system. Create a new Angular project:

ng new my-drupal-angular-app --strict

Navigate into your project directory:

cd my-drupal-angular-app

Step 2: Creating an Angular Service

Angular services are perfect for handling API calls. Let's create a service to fetch data from a Drupal JSON:API endpoint:

ng generate service article

This command generates a new service file. Open src/app/article.service.ts and configure it like so:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ArticleService {
  private apiUrl = 'https://example-drupal-site.com/jsonapi/node/article';

  constructor(private http: HttpClient) {}

  getArticles(): Observable<any> {
    return this.http.get<any>(this.apiUrl);
  }
}

This service injects Angular's HttpClient to make HTTP requests to Drupal's JSON:API.

Step 3: Displaying Articles in an Angular Component

Next, generate a component to display the articles. For simplicity, we'll use the default app.component.ts:

import { Component, OnInit } from '@angular/core';
import { ArticleService } from './article.service';

@Component({
  selector: 'app-root',
  template: `
    <div>
      <h2>Articles</h2>
      <ul>
        <li *ngFor="let article of articles">
          {{ article.attributes.title }}
        </li>
      </ul>
    </div>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  articles: any = [];

  constructor(private articleService: ArticleService) {}

  ngOnInit() {
    this.articleService.getArticles().subscribe((data: any) => {
      this.articles = data.data;
    });
  }
}

This component uses the Angular *ngFor directive to loop over and display the articles retrieved from Drupal.

Advanced: Using GraphQL with Angular

To fetch data using GraphQL, you'll need to set up Apollo Client for Angular. First, install Apollo Client and supporting libraries:

ng add apollo-angular
npm install graphql

Configure Apollo Client in your Angular application by editing src/app/graphql.module.ts:

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

export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
  return {
    link: httpLink.create({ uri: 'https://example-drupal-site.com/graphql' }),
    cache: new InMemoryCache()
  };
}

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

Now, use Apollo Client in your service or component to manage data with GraphQL queries.

Conclusion

In this lesson, you explored how to consume Drupal APIs within Angular applications, effectively combining Drupal's powerful backend with Angular's efficient frontend framework. Such integration enables the development of sophisticated, interactive applications with seamless data management capabilities.

In our next lesson, we'll explore using Redux or Vuex to manage state in your applications, particularly focusing on API data, ensuring a consistent and scalable state management strategy. Stay tuned for more!