Angular 4服务器端渲染ngx-bootstrap轮播使响应挂起

时间:2017-07-06 06:14:32

标签: node.js angular serverside-rendering

所以我试图在我的angular 4网站上实现服务器端渲染,我觉得我非常接近。除了1个特定路由和默认路由之外,我已经获得了渲染服务器端的所有路由。不起作用的路由是/ home,/任何未定义的路由,并且(所有负载都没有路由,但服务器端没有呈现主页)。

所以没有路线,只是没有得到我的捕获所有路线...任何未定义的东西我假设服务器没有正确处理默认路由...和/ home路线没有加载,对我来说没有意义。有什么提示吗?

这是我的server.ts

import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory';
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

const PORT = 4000;

enableProdMode();

const app = express();

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  console.log('url: ', options.req.url);
  const opts = { document: template, url: options.req.url };

  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.use(express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  console.log('caught by *');
  res.render('../dist/index.html', {
    req: req,
    res: res
  });
});
app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});

这是我的路由器

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';
import { ResourcesComponent } from './resources/resources.component';
import { ChurchesComponent } from './churches/churches.component';
import { GetAQuoteComponent } from './get-a-quote/get-a-quote.component';

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'services',
    component: ServicesComponent
  },
  {
    path: 'resources',
    component: ResourcesComponent
  },
  {
    path: 'about',
    component: AboutComponent
  },
  {
    path: 'churches',
    component: ChurchesComponent
  },
  {
    path: 'get-a-quote',
    component: GetAQuoteComponent
  },
  {
    path: '**', 
    component: HomeComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

1 个答案:

答案 0 :(得分:0)

好消息,我弄清楚为什么一条路线/随机路线没有加载。 ngx-bootstrap轮播(我在我的家乡路线上)有一个需要在服务器端禁用的间隔。否则路线将永远挂起并永不加载。

参考:https://github.com/valor-software/ngx-bootstrap/issues/1353

最后,无路由无效的事实是因为我的静态资产路由在我的express.get之前拦截了请求。