0

I'm developing a website for managing information in the form of dashboards. Each dashboard will have the url of /dashboard/something1/something2, /dashboard/something3/something4. I've been trying to find a solution to handle every url dynamically by calling APIs based on the url, and display the data in the same component but none seems to work properly.

I've tried ActivatedRoute but I read that since it's something outside of the <router-outlet>, it will probably return empty url. I've also tried activatedRoute.snapshot['_routerState'].url but I don't think this is the proper way to handle it. I'm also trying to use just router.url

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
  selector: 'ngx-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss'],
})
export class DashboardComponent implements OnInit {
  data: string;

  constructor(private router: Router) {
    this.router.events.subscribe(e => {
      if (e instanceof NavigationEnd) {
        this.url = this.router.url;

        //then use the url params to call APIs and fill in data
      }
    });
  }

  ngOnInit() {}
}

What's the proper way to get the url of each route and is there any other solution for me to handle different views in the same component dynamically in general?

  • Can you use parameterized routing? Match the component to the path '/dashboard/:param1/:param2' and then get the parameter information out of the route when the component loads. For an example, see this part of the Angular tutorial: https://angular.io/tutorial/toh-pt5#navigating-to-hero-details. – codequiet May 24 '19 at 15:38
  • In addition to what @codequiet said, you would then inject the `ActivatedRoute` from `@angular/router` and then subscribe to `route.params` to be able to respond to the changes. See this question for a similar answer: https://stackoverflow.com/questions/56268468/router-link-is-not-loading-another-page-with-different-placeholder-is-this-the – pjlamb12 May 24 '19 at 16:07
  • This might be exactly what I needed. Thank you guys! – Tuấn Phong May 25 '19 at 11:37

0 Answers0