Angular universal-starter prerender with 4 levels 嵌套参数

Angular universal-starter prerender with 4 levels nesting parameters

出于某些原因,我想使用 https://github.com/angular/universal-starter 而不是服务器端渲染来创建我的 angular 5 项目的预渲染版本。

我的路线有 4 个级别,如下所示:

example.com/category/:id/subcategory/:id/event/:id/ticket/:id

另外,还有一个 api 后端,我用它来为每个部分获取数据。例如,/category/1 是运动,/category/1/subcategory/1 是足球等等。

第一个问题:如何使用prerender.js为每个级别创建一个html文件,我的static.paths.ts应该如何长什么样?

第二个问题:如何为每个页面设置元标记?

第三个问题:我的app-routing.module应该是什么样子的?我应该使用 children 方法吗?

我正在使用 Angular 5.0.0 和 ngx-restangular 2.0.2

谢谢。

prerender 和 运行time 服务器端渲染的设置大部分相似,唯一的区别是一个是静态的,另一个是动态的。您仍将配置 Universal 需要您设置的所有内容才能正常工作。

在我回答您的问题之前,我强烈建议您按照 this (step-by-step configurations) and this(关于 Angular Universal 陷阱的有用部分)指南来配置 Angular Universal,因为它是我读过的更全面和最新的文章。


First question: How can I create a html file for each of these levels by using prerender.js and How should my static.paths.ts look like?

您的 static.path.ts 应包含您要预呈现的所有路线:

export const ROUTES = [
  '/',
  '/category/1/subcategory/1/event/1/ticket/1',
  '/category/1/subcategory/1/event/1/ticket/2',
  ...
];

看起来很乏味吧?这是静态生成 HTML 而不是灵活的 运行 时间服务器端呈现的权衡。您可以而且可能应该编写自己的脚本来生成您的应用程序可用的所有路由(查询数据库、生成所有可能的值等)以预呈现您想要的所有页面。

Second question: How can I set meta tags for each of these pages?

与您设置元标记或任何 Angular 应用程序的方式没有什么不同,您可以使用 Angular 提供的 Title and Meta 服务。

示例:

constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
    private meta: Meta,
    private title: Title,
    private pageMetaService: PageMetaService
) { }

ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
        this.title.setTitle((`${this.article.title} - Tilt Report`));

        let metadata = [
            { name: 'title', content: 'Title' },
            { name: 'description', content: 'This is my description' },
            { property: 'og:title', content: 'og:Title' },
            { property: 'og:description', content: 'og:Description' },
            { property: 'og:url', content: 'http://www.example.com' },
        ];
        metadata.forEach((tag) => { this.meta.updateTag(tag) });
    };
}

Third question: How should my app-routing.module look like? Should I use children approach

您可以选择使用或不使用 'children' 方法,我认为这是延迟加载模块。当您配置 Angular Universal 时,您应该进行某些设置以使延迟加载模块能够在服务器端工作。