menu component
import { QueryParam } from "./query-param";
import { QueryRouterLink } from "./query-router-link";
export class Menu {
link: string;
name: string;
queryParam: QueryParam[];
queryRouterLink?: QueryRouterLink;
}
QueryParam class
export class QueryParam {
name: string;
value: string;
}
QueryRouterLink class
export class QueryRouterLink {
[name: string]: string;
}
service for handling links
import { Injectable } from "@angular/core";
import { Menu } from "../classes/menu";
import { QueryParam } from "../classes/query-param";
import { QueryRouterLink } from "../classes/query-router-link";
@Injectable({
providedIn: "root",
})
export class LinksService {
constructor() {}
queryRouterLink: QueryRouterLink;
autoMenu() {
let myMenu: Menu[] = [
{
link: `/componentOne`,
name: "Component One",
queryParam: [{ name: "resource", value: "Component One" }],
},
{
link: `/componentTwo`,
name: "Component Two",
queryParam: [{ name: "resource", value: "Component Two" }],
},
];
for (let menuItem of myMenu) {
menuItem.queryRouterLink = this.getCorrectQueryParam(
menuItem.queryParam as QueryParam[]
);
}
return myMenu;
}
getCorrectQueryParam(queryParam: QueryParam[]) {
for (let param of queryParam) {
this.queryRouterLink[param.name] = param.value;
}
return this.queryRouterLink;
}
}
Error Handling in QueryParams Conversion
getCorrectQueryParam will convert a queryParam with name: 'resource' and value: "Component Two" to the usual QueryParams [name: string]: string.
The error message received is "Cannot set property 'resource' of undefined." This could indicate that 'name' is undefined or that there is an issue with the function's logic. Further debugging may be required.</p>
<p>app.html setup</p>
<pre><code> <mat-toolbar>
<h1
*ngFor="let item of menu"
[routerLink]="item.link"
[queryParams]="item.queryRouterLink"
>
{{ item.name }}
</h1>
</mat-toolbar>
<router-outlet></router-outlet>
app.ts file
import { Component, OnInit } from "@angular/core";
import { LinksService } from "./services/links.service";
import { Menu } from "./classes/menu";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"],
})
export class AppComponent implements OnInit {
title = "training";
menu: Menu[];
constructor(private linkS: LinksService) {}
ngOnInit() {
this.menu = this.linkS.autoMenu();
}
}