【问题标题】:How to load a feature module (lazyloaded module) without SSR in Angular?如何在 Angular 中加载没有 SSR 的功能模块(延迟加载模块)?
【发布时间】:2021-10-14 06:30:33
【问题描述】:

Angular 开发者! 我正在开发一个 Angular 应用程序,其中需要从服务器端渲染许多路由,在 Angular 中称为 Angular Universal (SSR)。但是,在我的应用程序中,有很多私有路由和特性模块实际上不需要从服务器呈现。如果他们在客户端渲染就可以了。这些实际上是私有路由,例如用户配置文件、用户配置文件编辑模块。

保护这些路由不被服务器渲染的方法是什么。或者有什么方法可以让路由只在客户端渲染?

【问题讨论】:

标签: angular server-side-rendering angular-universal


【解决方案1】:

这个答案来自 eneajaho 来自 reddit。

嗨,几个月前我遇到了您的用例,我“找到”了一个解决方案,并且还在 Angular 存储库中打开了一个问题,以便在文档中添加解决方案,但没有成功。无论如何,这是问题所在:https://github.com/angular/angular/issues/41187

解决方案:您应该编辑发生服务器端路由的server.ts 文件,并添加一组您不想在服务器端呈现的路由。示例:

const EXCLUDED_ROUTES: string[] = [
  '/test',
  '/auth(/)?*',
  '/back(/)?*',
];

然后,您应该在文件中添加一个包含排除路由的 get,在服务器呈现应用程序之前。而且这个路由会直接返回 index.html 文件,所以不会渲染它,而是将它作为一个静态文件,就像客户端渲染一样。

server.get(EXCLUDED_ROUTES, (req, res) => {
  res.sendFile(join(distFolder, 'index.html'));
});

整个代码:

/**
 * EXCLUDED_ROUTES contains all the paths that we don't want to render on the server
 *  Examples:
 *    '/test'
 *    '/back(/)?*' // regex: string starts with /back, '/' is optional, '*' it can be anything
 */
const EXCLUDED_ROUTES: string[] = [
  '/test',
  '/auth(/)?*',
  '/back(/)?*',
];

/**
 * Is used to exclude the routes from rendering on the server. Ex. Auth Page, Admin Page
 * To add or remove excluded routes modify the EXCLUDED_ROUTES array
 */
server.get(EXCLUDED_ROUTES, (req, res) => {
  res.sendFile(join(distFolder, 'index.html'));
});

【讨论】:

    猜你喜欢
    • 2017-02-22
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    相关资源
    最近更新 更多