我正在通过学习this example app来学习Angular 7 。该示例应用程序使用通配符路由来处理所有未处理的路由。
具体来说,这个app-routing.module.ts将所有杂项路由定向至 AppConfig.routes.error404 ,由 Error404PageComponent.ts 处理,最终提供 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 uperror404-page.component.html
for every non-specified route. However, we would be adding logic to give special handling insideError404PageComponent
for a specific static route in addition to the logic for every non-specified route.
这里的目标是能够处理静态路由,而不必为每个路由创建单独的组件。例如,想象一个博客,其中大多数路由都具有相同的模板,但每个博客条目中的内容不同。
最佳答案
模板在构建时编译到组件中,您将无法更改组件在运行时使用的模板,但您可以根据条件隐藏和显示部分。将路由器注入(inject)到您的组件中
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>
关于javascript - Angular 7 中静态内容的通配符路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56159946/