首页 > 解决方案 > 如何动态更改网址

问题描述

我用来从 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?

标签: angularangular8

解决方案


不推荐,因为您需要在路线列表中添加所有路线,但这是可能的。你只需要在路由器的帮助下更新 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

推荐阅读