Angular 7 中静态内容的通配符路由

Wildcard route for static content in Angular 7

我正在通过学​​习 this example app 来学习 Angular 7。示例应用程序使用通配符路由来处理所有其他未处理的路由。

具体而言,此 app-routing.module.ts directs all miscellaneous routes to AppConfig.routes.error404, which is handled by Error404PageComponent.ts, which then ultimately serves up error404-page.component.html 用于未由其自身组件和命名路由指定的所有可能路由。

What specific changes would need to be made to the code in this sample app in order for the wildcard route serve different static content for different submitted routes?

例如,如果网络用户输入路由 /i-am-a-jelly-donut,需要进行哪些更改才能使请求 1.) 继续通过 Error404PageComponent.ts,但是用户的浏览器收到新的 i-am-a-jelly-donut.page.html 而不是 error404-page.component.html 视图?

The Error404PageComponent.ts would still serve up error404-page.component.html for every non-specified route. However, we would be adding logic to give special handling inside Error404PageComponent for a specific static route in addition to the logic for every non-specified route.

这里的目标是能够处理静态路由,而不必为每条路由创建单独的组件。例如,考虑一个博客,其中大多数路由具有相同的模板,但每个博客条目中的内容不同。

模板在构建时编译到组件中,您无法在运行时更改组件使用的模板,但您可以根据条件隐藏和显示部分。将路由器注入您的组件

constructor(private router: Router) {}

现在您可以根据路由是否包含 'i-am-a-jelly-donut'

在您的组件上设置一个变量
jellyDonut = this.router.url.indexOf('i-am-a-jelly-donut') !== -1;

并在您的模板中

<ng-container *ngIf="jellyDonut">
  Jelly Donut
</ngcontainer>

<ng-container *ngIf="!jellyDonut">
  Other stuff
</ngcontainer>