Search code examples
angularangular-routing

Angular Router Use Same Component


I have two pages that I want to use the same component for each of the two paths. The reason is that I share the header which has two search fields for the main component. Whenever I change the page, I keep getting additional calls to the service. The first time 2, the second time 4, the third time 6...I just want the page to start over. This is what is happening the constructor. All I do is show/hide the library and detail page based on the route url.

  this.router.events.subscribe((val) => {
      if (val instanceof NavigationEnd) {
          let urlArray = val.url.split('/');
          if (urlArray[1] === 'library') {
              this.detail = false;
          } else if (urlArray[1] === 'detail') {
              this.searchById(urlArray[2]);
          }
      }
  });

Basically the library component has a list of books, that when clicked on go to a details page for that book. I show/hide the library and detail page

const appRoutes: Routes = [
  { path: 'library', component: LibraryComponent },
  { path: 'detail/:id',      component: LibraryComponent },
  { path: '',   redirectTo: '/library', pathMatch: 'full' }
];

Here is the service call, it just returns dummyJSON data

  searchById(id)  {

  this.mainService.searchById(id).subscribe(
      data => { this.detail = true; this.bookdata = data; console.log(data); },
      err => { },
          () => { }
)};

Solution

  • I just unsubscribed from the router event after it came back.

          const routerEvent = this.router.events.subscribe((val) => {
          if (val instanceof NavigationEnd) {
              let urlArray = val.url.split('/');
              if (urlArray[1] === 'library') {
                  this.detail = false;
              } else if (urlArray[1] === 'detail') {
                  this.searchById(urlArray[2]);
              }
              routerEvent.unsubscribe();
          }
      });