angular universal 17 prerender dynamic content

Discussão em 'Angular' iniciado por Jeff Sloyer, Abril 16, 2025.

  1. Jeff Sloyer

    Jeff Sloyer Guest

    With Angular 17 prerendering is available, what I haven't been able to determine from the Angular docs is how to use dynamic content from an external API to drive the prerendered routes.

    Routes:

    export const routes: Routes = [
    {
    path: '',
    component: HomeComponent,
    title: 'Home page'
    },
    {
    path: 'article/:id',
    component: ArticleDetailsComponent,
    title: 'Article Details'
    }
    ];


    I have a mock data service and these routes are prerendered. However I can't figure out how to call my REST API for my CMS at build time. The CMS is called fine at run time but that content isn't available during build time. My mock homepage links to 3 articles, /article/1, /article/2, and /article/3

    article.service.ts

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

    articleList: Article[] = [
    {
    id: 1,
    title: 'my article time',
    subTitle: 'sub title'
    }
    ...
    ]

    getArticleById(id: number): Article | undefined {
    let article = this.articleList.find(article => article.id === id);

    //ideally long term this is done upstream by a performant go app
    if (article !== undefined) {
    article = this.transformContent(article);
    }

    return article;
    }


    getArticleFromCMS(): Observable<Content> {
    return this.http.get<Content>('https://example.com')
    .pipe(
    catchError(this.handleError<Content>('getArticle', {}))
    );
    }


    article-details.component.ts

    import { Component, inject } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { ActivatedRoute } from '@angular/router';
    import { ArticleService } from '../article.service';
    import { Article, CMSContent } from '../article';

    @Component({
    selector: 'app-article-details',
    standalone: true,
    imports: [CommonModule],
    templateUrl: './article-details.component.html',
    styleUrl: './article-details.component.css'
    })
    export class ArticleDetailsComponent {
    route: ActivatedRoute = inject(ActivatedRoute);
    articleService = inject(ArticleService);
    article: Article | undefined;
    cmsContent: CMSContent | undefined;

    constructor() {
    const articleID = Number(this.route.snapshot.params['id']);
    this.article = this.articleService.getArticleById(articleID);
    }

    ngOnInit(): void {
    this.getArticles();
    }

    getArticles(): void {
    this.articleService.getArticleFromCMS()
    .subscribe(article => this.cmsContent = article.content[0]);
    }
    }

    Continue reading...

Compartilhe esta Página