如何在Angular中建立友好的路线?
我试图用角度建立友好的路线。 例如,我需要这样的东西:
example.com/my-post-title
代替:
example.com/post/23
谢谢!
I am trying to make friendly routes in angular.
For example, I would need something like this:
example.com/my-post-title
instead of:
example.com/post/23
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我想提及为什么将URL从
example.com/post/23
更改为example.com/my-post-title
是一个坏主意。 URL的23
很可能是该帖子的唯一标识符,应加载。如果我们像您想要的那样替换URL,则标识符已消失,在重新加载或直接使用example.com/my-post-title
直接访问URL之后,除非您挖掘您的发布并搜索特定标题。我建议在标识符之后添加更人性化的文本。这样,URL适用于人类和您的应用。因此,URL看起来像
example.com/post/23/my-post-title
更改路线
1。首先 ,我们需要在slug的路由下添加一个参数,因此我们可以fetch稍后,当相应的组件已加载时,检查是否已经附加了sl。但是,您将需要两条路线,其中仅输入ID,如果用户访问没有SLUG的URL,另一个则包括SLUG参数。
因此,您的路线应该看起来像这样:
2。在组件加载后加载后替换项目组件中的URL
,我们想检查是否设置了slug参数,如果没有设置,则将其添加到URL中
router.navigate()
的选项。使用替换
,我们可以在不重新加载页面或将任何条目添加到浏览器历史的情况下操纵URL。现在,您的组件应在url
example.com/post/23
访问example> example.com/post/23/my-post-title
时添加slug 呢这是一个工作的stackblitz示例:
https:// https ://stackblitz.com/edit/ angular-ivy-yudqtn?file = src/app/app.component.ts
希望我有帮助,
Tkay勋爵
At first I wanna mention why changing the URL from
example.com/post/23
toexample.com/my-post-title
is a bad idea. The23
of your URL is most likely a unique identifier for the post, that should be loaded. If we replace the URL like you want to, the identifier is gone and after a reload or accessing the URL directly withexample.com/my-post-title
wouldn't work, unless you dig through your posts and search for the specific title.I would recommend to add the more human readable text after the identifier. That way the URL is readable for a human and your application. So the URL would look like
example.com/post/23/my-post-title
1. Changing the route
At first we need to add a parameter to the route for the slug, so we can fetch the slug later when the corresponding component has loaded, to check if the slug is already appended or not. But you will need two routes, one where only the ID is entered, if the user visits the URL without the slug, and one that includes the slug-parameter.
So your route should look something like that:
2. Replace the URL in the Item-Component
When the Post-Component loads, we wanna check if the slug parameter was set and if not, add it to the URL with the
replaceUrl
option of theRouter.navigate()
. With thereplaceURL
we can manipulate the URL without reloading the page or adding any entries to the browser-history.And now your components should add the slug when it is visited by the URL
example.com/post/23
toexample.com/post/23/my-post-title
!Here is a working StackBlitz example:
https://stackblitz.com/edit/angular-ivy-yudqtn?file=src/app/app.component.ts
Hope I was of help,
Lord Tkay