How could I check if the URL/route in the browser is related to the path mask?

Discussão em 'Angular' iniciado por Ivan Ferrer, Dezembro 11, 2024.

  1. Ivan Ferrer

    Ivan Ferrer Guest

    My goal is to try to create an ID rule that allows you to check in the HTML where it is within a category (id), it must mark the menu, this id is replicated for several different routes, but it has to validate the ID and the route with the URL that is being accessed, it being the same URL that is within the routes file and having the same ID, the menu that has the type that I pass as ID, it will return true.

    When accessing the link: page/id/1234

    I need to identify data => id => 'page-data-x'

    In my routes module I have this structure:

    {
    path: 'page',
    children: [
    {
    path: 'id/:id',
    component: PageComponent,
    canActivate: [AuthGuard],
    data: {
    id: 'page-data-x',

    }
    },
    {
    path: 'category/:id/id/:id',
    component: PageComponent,
    canActivate: [AuthGuard],
    data: {
    id: 'page-data-y',

    }
    }]
    }


    Inside the class I have a constructor that receives the ID and the current URL:

    contentID: any;
    currentURL: string;

    constructor(
    private router: Router,
    private route: ActivatedRoute) {
    //ACCESS to ID
    this.contentID = this.route.snapshot.data?.id;
    //Current route
    this.currentURL = this.route.snapshot.pathFromRoot[0]['_routerState'].url

    }


    These are my failed attempts:

    isActiveRoute(type: string): boolean {
    // Gera a rota esperada em formato string
    const targetRoute = this.routerLink(type);
    const targetRouteString = Array.isArray(targetRoute) ? targetRoute
    .filter(segment => typeof segment !== 'object')
    .join('/')
    .replace(/\/\//gi, '/') : targetRoute;

    const currentRoute = this.router.url.split('?')[0].split(';')[0];

    const children = (this.route.snapshot.routeConfig?.children || []).filter(
    (child) => child.data?.id
    );

    const isMatchingPath = (child: any): boolean => {
    if(child.path) {
    const regexPattern = '^' + child.path.replace(/:[^/]+/g, '[^/]+') + '$';
    const regex = new RegExp(regexPattern);
    return regex.test(currentRoute) && child.data?.id === type;
    }
    };


    const matchingChild = children.find(child => isMatchingPath(child));

    if (matchingChild) {
    return true;
    }


    const routeDataId = this.route.snapshot.data?.id;
    const routePath = this.route.snapshot.routeConfig?.path;

    if (routeDataId === type && routePath && currentRoute.includes(routePath)) {
    return true;
    }

    return currentRoute.includes(targetRouteString);

    }



    routerLink(type: string) {

    this.queryParams = this.routerParams[type];

    switch (type) {
    case 'dashboard':
    return ['page', 'dasnboard'];
    ...
    }
    }

    Continue reading...

Compartilhe esta Página