Angular 通用 17 预渲染动态内容

问题描述 投票:0回答:1

随着 Angular 17 预渲染可用,我无法从 Angular 文档中确定如何使用外部 API 中的动态内容来驱动预渲染路由。

路线:

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

我有一个模拟数据服务,这些路线是预渲染的。但是,我不知道如何在构建时为我的 CMS 调用 REST API。 CMS 在运行时调用正常,但该内容在构建期间不可用。我的模拟主页链接到 3 篇文章,

/article/1
/article/2
/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]);
  }
}


angular angular-universal static-site-generation
1个回答
0
投票

我参考了文档

Prerendering parameterized routes

我创建了一个文件

routes.txt

/article/1
/article/2
/article/3

然后我将文件添加到 angular.json 中,如下所示

…
"architect": {
  "build": {
    "builder": "@angular-devkit/build-angular:application",
      "options": {
        "prerender": {
          "routesFile": "routes.txt"
        },
      },
…

当我运行

ng build
时,我看到为
routes.txt

中指定的路线创建了文件夹

请从 stackblitz 找到下面的工作示例,其中包含包含预渲染路线的

dist
文件夹!

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.