Blog>
Snippets

Integrating Angular Universal with a Headless CMS for SEO

Provide an example of integrating a headless CMS with Angular Universal for pre-rendering content-rich pages that improve SEO.
import { TransferHttpCacheModule } from '@nguniversal/common';

@NgModule({
  imports: [
    // ... other modules
    TransferHttpCacheModule,
    // ... other modules
  ],
  // ... rest of the module configuration
})
export class AppModule { }
This code snippet is part of the AppModule where TransferHttpCacheModule is imported from '@nguniversal/common'. This module is essential for caching HTTP requests on the server-side, which is important for SEO as it speeds up the rendering process for crawlers.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class CmsService {
  constructor(private http: HttpClient) { }

  getContent(slug: string) {
    return this.http.get(`https://your-headless-cms.com/content/${slug}`);
  }
}
This code defines a CmsService in Angular that uses HttpClient to fetch content from a headless CMS. The getContent method takes a slug as an argument and makes a GET request to the appropriate endpoint of the headless CMS.
import { Component, OnInit } from '@angular/core';
import { CmsService } from './cms.service';

@Component({
  selector: 'app-content-page',
  template: '<div [innerHTML]="content"></div>',
  styles: []
})
export class ContentPageComponent implements OnInit {
  content: string;

  constructor(private cmsService: CmsService) { }

  ngOnInit() {
    this.cmsService.getContent('your-page-slug').subscribe(data => {
      this.content = data.content;
    });
  }
}
This component ContentPageComponent uses the CmsService to fetch content when it initializes. The fetched content is assigned to a property named content and is then rendered into the view using Angular's innerHTML binding, which allows dynamic HTML content to be safely injected into the template.
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    AppModule,
    ServerModule,
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule { }
This code sets up the AppServerModule which is used for server-side rendering with Angular Universal. It imports the AppModule to include all the components and services. It also imports ServerModule from '@angular/platform-server' which provides server versions of Angular directives such as title and meta for managing SEO-related elements.