Angular universal-starter - prerender组件多次使用不同的数据

时间:2017-10-24 14:20:46

标签: angular angular2-routing prerender angular-universal

我正在尝试使用官方通用启动项目中的 prerender.ts 来为所有路径参数渲染一个组件。我有一个工作角度应用程序,其工作方式类似于包含许多文章链接的首页的报纸。文章显示在它自己的组件中,根据路由参数我得到数据。

{
    path: 'artikel/:id',
    component: ArticleComponent,
    data: {title: environment.pageName + ' - Artikel'},
    resolve: {article: ArticleResolveService},
},

现在让我的应用程序SEO友好我使用角度的Universal Starter将我的组件预渲染到静态html文件。我的基本组件得到预渲染,但我尝试为每篇文章多次渲染文章组件。目前我的prerender.ts看起来像这样:

// Load zone.js for the server.
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { join } from 'path';

import { enableProdMode } from '@angular/core';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
import { renderModuleFactory } from '@angular/platform-server';
import { ROUTES } from './static.paths';

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main.bundle');

const BROWSER_FOLDER = join(process.cwd(), 'browser');

// Load the index.html file containing referances to your application bundle.
const index = readFileSync(join('browser', 'index.html'), 'utf8');

let previousRender = Promise.resolve();

// Iterate each route path
ROUTES.forEach(route => {
  var fullPath = join(BROWSER_FOLDER, route);

  // Make sure the directory structure is there
  if(!existsSync(fullPath)){
    mkdirSync(fullPath);
  }
  // Writes rendered HTML to index.html, replacing the file if it already exists.
  previousRender = previousRender.then(_ => renderModuleFactory(AppServerModuleNgFactory, {
    document: index,
    url: route,
    extraProviders: [
      provideModuleMap(LAZY_MODULE_MAP)
    ]
  })).then(html => writeFileSync(join(fullPath, 'index.html'), html));
});

ROUTES的定义如下:

export const ROUTES = [
    '/home',
    '/suche',
    '/artikel'
];

这会生成以下输出。我已经标记了我最终想要达到的目标:

/dist
|
+-- home
  |
  +--index.html
+-- suche
  |
  +--index.html
+-- article(as it is right now)
    |
    +-- index.html
+-- article(as it should be)
    |
    +-- 90(id from article - see routing)
        |
        +--index.html
    +-- 91
        |
        +--index.html
    +-- 92
        |
        +--index.html

每个index.html都应该包含prerenderd article.component和相应的数据

0 个答案:

没有答案