Honey
Honey

Reputation: 13

Angular routerLink with parameters is changing the URL but not navigating or reloading

it changes the url but does not reload

I am basically trying to reload the page but with a diff data.

post.component.ts

constructor(private postService :PostService, private activateRoute: ActivatedRoute)
  
    {}

private getPostsbyCategory(){
          this.postService.getPostsByCategory(this.catid).subscribe((data:PostModel[]) => {
            this.postbycategory = data;
            console.log(data)
          }, error => {
            throwError(error);}
            // 
          );}


 ngOnInit() {

    this.id = this.activateRoute.snapshot.params.id;
    this.catid = this.activateRoute.snapshot.params.catid;

    console.log(this.id);
    console.log(this.catid)
    this.getposts();
    this.getPostsbyCategory();

post.component.html

 <a routerLink="/view-post/{{post.catid}}/{{post.id}}" class="card">

here is the routing file app-routing.module.ts

 import { NgModule,Component } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { ReactiveFormsModule } from '@angular/forms';
    import { FormsModule } from '@angular/forms';
    import { TestComponent } from './test/test.component';
    
    import { HomeComponent } from './home/home.component';


    import { ViewPostComponent } from './component/post/view-post/view-post.component';
    import { ViewCategoryComponent } from './component/category/view-category/view-category.component';
    const routes: Routes = [
    
      { path: '', component: HomeComponent },
      {path: 'home', component: HomeComponent },
      {path: 'test', component: TestComponent },
      {path: 'topics', component: ListTopicsComponent },
      { path: 'view-topics/:id', component: ViewTopicsComponent },
      {path : 'view-post/:catid/:id', component:ViewPostComponent}, 
    
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes , {onSameUrlNavigation: 'reload'})],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }

it changes the url but does not reload I am basically trying to reload the page but with a diff data.

Upvotes: 1

Views: 2026

Answers (2)

Juano7894
Juano7894

Reputation: 830

you should do the following:

  ngOnInit(): void {

    this._route.paramMap.subscribe((params: ParamMap) => {
      
      this.id = params.get('id');
      this.catId = params.get('id');
      
      console.log(this.id);
      console.log(this.catid);

      this.getposts();
      this.getPostsbyCategory();
    });
  }

With this you are listening to route param changes. So each time you call routerLink with new params, this code is going to be executed.

Regards

Upvotes: 1

TheBugger
TheBugger

Reputation: 41

Try enclosing the link inside a set of square brackets, and put the link itself inside single quotes .

 <a routerLink="['/view-post/{{post.catid}}/{{post.id}}']" class="card">

Upvotes: 0

Related Questions