angular - 如何动态更改网址
问题描述
我用来从 url 的参数中获取我的博客数据,如下所示。
const id = this.route.snapshot.paramMap.get('id');
const newurl = `${serverUrl}/${id}`;
// this.http.get<any>(newurl); // to get data from the server.
网址如下所示
http://localhost:4200/blogs/1
http://localhost:4200/blogs/2
http://localhost:4200/blogs/3
现在,在我从服务器获取数据后,我想在 url 的末尾添加博客标题,如下所示。
http://localhost:4200/blogs/1/First-Title-Url
http://localhost:4200/blogs/2/Second-Title-Url
http://localhost:4200/blogs/3/Third-Title-Url
从字面上看,我对最后在 url 中添加的标题什么都不做,而是为了便于阅读。
这是我在后端的博客类
public class Blog
{
[Key]
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
}
注意:标题有重复。
我在 Asp.Net Core 2.2、Angular 8 中运行这个项目。我现在如何更改 url?
解决方案
不推荐,因为您需要在路线列表中添加所有路线,但这是可能的。你只需要在路由器的帮助下更新 url,你可以像这样在构造函数中注入,
constructor(private router: Router,
private route: ActivatedRoute) {
}
然后从您的 API 获得响应后,您只需要导航到更新的 url,
this.http.get<any>("API_URL_HERE").subscribe(data => {
this.router.navigate([`./${data.title}`],
{
relativeTo: this.route
});
});
这会将您导航到此 url,但请记住,所有这些 url 都必须在您的RoutingModule中声明。如果您认为不可能在 routes 数组中声明所有 url,那么您必须改用查询参数。
http://localhost:4200/blogs/1/First-Title-Url
推荐阅读
- python - 更改字典 Python 中的变量
- gulp - 使用 Gulp.src 复制隐藏文件夹
- reactjs - 如何在 React 项目中添加 p5.clickable 和 p5.gui 等 p5.js 社区库?
- javascript - React + Firebase:提交按钮未触发?
- ruby - Ruby on Rails 通过表单错误将对象添加到数据库
- vba - DoCmd.OpenQuery 位于何处
- mysql - 从 nginx conf 文件调用 mysql DB
- wordpress - 在 Woocommerce 侧边栏区域上方移动 Woocommerce 特色类别图片
- sql - Power BI 报表生成器指标公式
- r - 如何在 floor_date 函数后每 8 行检查一次时间是否相似(并在需要时进行更正)