Blog>
Snippets

Creating a Sitemap.xml Dynamic Generator with Angular

Exhibit how to implement a dynamic sitemap.xml generator using server-side scripts in Angular to enhance SEO and ensure search engines can effectively index the pre-rendered pages.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  generateSitemap(pages: string[]): string {
    const domain = 'https://www.yourdomain.com';
    let sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`;
    pages.forEach(page => {
      sitemap += `
  <url>
    <loc>${domain}/${page}</loc>
    <changefreq>weekly</changefreq>
    <priority>0.8</priority>
  </url>`;
    });
    sitemap += `
</urlset>`;
    return sitemap;
  }

  // This function would be used to send the sitemap to the server to be saved
  uploadSitemap(sitemap: string) {
    return this.http.post('/api/sitemap', { sitemap });
  }
}
This SitemapService class provides methods to generate a sitemap.xml content and upload it to the server. It takes an array of page routes, constructs the sitemap XML content, and provides a method to send this content to the server using HttpClient.
import { SitemapService } from './sitemap.service';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  constructor(private sitemapService: SitemapService) { }

  public generateAndUploadSitemap() {
    // Fetch list of available pages or define it.
    const pages = ['home', 'about', 'products', 'contact'];
    const sitemap = this.sitemapService.generateSitemap(pages);

    // Upload the sitemap to the server
    this.sitemapService.uploadSitemap(sitemap).subscribe(response => {
      console.log('Sitemap uploaded successfully:', response);
    }, error => {
      console.error('Failed to upload sitemap:', error);
    });
  }
}
AppService is using the SitemapService to generate a sitemap.xml file and upload it to the server. It provides a method to carry out the whole process including generation of the XML content and the HTTP POST call to upload the data.