如何动态更改 url

How to change url dynamically

我曾经从 url 的参数中获取我的博客数据,如下所示。

const id = this.route.snapshot.paramMap.get('id');
const newurl = `${serverUrl}/${id}`;
// this.http.get<any>(newurl); // to get data from the server.

url往下看

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 中最后添加的标题没有做任何事情,但为了便于阅读。

这是我在 back-end

中的博客 class
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?

您可以使用 queryParam 来实现。

constructor(private _router: Router) { }

this.http.get<any>(newurl).subscribe(data => {
      this._router.navigate(
        [],
        {
          relativeTo: this._route,
          queryParams: { title: data.title },
          queryParamsHandling: 'merge'
        });
})

这将产生 url 如:

http://localhost:4200/blogs/1?title=First-Title-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 中声明。如果您认为不可能在路由数组中声明所有 url,那么您必须改用查询参数。

http://localhost:4200/blogs/1/First-Title-Url

您可以使用嵌套的 switchMap 运算符根据您从第一个请求获得的标题创建另一个请求。如果 paramMap 在完成之前发生更改,switchMap 运算符会取消所有待处理的请求。

const blog$ = this.route.paramMap.pipe(
  switchMap((params) => {
    const url = `${serverUrl}/${params.get('id')}`;
    return this.http.get(url).pipe(
      switchMap((blogTitle) => this.http.get(`${url}/{blogTitle}`))
    );
  })
)

然后你可以使用blog$来异步显示内容,例如像

<ng-container *ngIf="blog$ | async as blog">
  <h1>{{blog.title}}</h1>
  <p>{{blog.body}}</p>
</ng-container>

每当您更改路线(更准确地说:路线 paramsMap)时,它都会自动重新加载博客。