Search code examples
angularangular8

How to change url dynamically


I use to get my blog's data from url's param like below.

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

url looks below

http://localhost:4200/blogs/1
http://localhost:4200/blogs/2
http://localhost:4200/blogs/3

Now, after I get the data from the server, I would like to add blog title at the end of url like below.

http://localhost:4200/blogs/1/First-Title-Url
http://localhost:4200/blogs/2/Second-Title-Url
http://localhost:4200/blogs/3/Third-Title-Url

Literally I do nothing with lastly added title in the url but to readable purpose.

Here is my Blog class in back-end

public class Blog
{
    [Key]
    public int id { get; set; }
    public string title { get; set; }
    public string body { get; set; }
}

Note: title have duplicates.

I am running this project in Asp.Net Core 2.2, Angular 8. How do I change url now?


Solution

  • You can use queryParam to achieve this.

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

    This will produce url like:

    http://localhost:4200/blogs/1?title=First-Title-Url