I offer a unique service that creates custom toolbars with a variety of classes to choose from

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();
  }
}

Answer №1

Here is the provided solution:

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;  <===== incorrect

  autoMenu() {
    let myMenu: Menu[] = [
      {
        link: `/componentOne`,
        name: "ComponentOne",
        queryParam: [{ name: "resource", value: "ComponentOne" }],
      },
      {
        link: `/componentTwo`,
        name: "ComponentTwo",
        queryParam: [{ name: "resource", value: "ComponentTwo" }],
      },
    ];

    for (let menuItem of myMenu) {
      menuItem.queryRouterLink = this.getCorrectQueryParam(
        menuItem.queryParam as QueryParam[]
      );
    }

    return myMenu;
  }

  getCorrectQueryParam(queryParam: QueryParam[]) {
    let queryRouterLink: QueryRouterLink = {}; <====correct 
    for (let param of queryParam) {
      this.queryRouterLink[param.name] = param.value;
    }
    return this.queryRouterLink;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting the tabindex issue with buttons in MatMenu in Angular

I am currently using Angular 17 in my project and I am working on adding ADA compliance to it by placing tabindex where needed. However, I am encountering an issue with a button inside a mat menu. The tabindex="0" attribute is not focusing on th ...

Within Vuex, the object store.state.activities contains a specific key labeled "list" which initially holds an array of three items. However, when attempting to access store.state.activities.list directly, an empty array

My project is utilizing Vue. The store.state.activities object contains 2 keys, including an array named list with 3 elements. However, despite attempting to access it using store.state.activities.list, I am getting an empty array. I have experimented w ...

Exchange data using socket.io in nodejs and express with a different javascript file

Imagine having a JavaScript file that needs to interact with another JavaScript file in order to share data between them. For instance, let's consider a file named game_server.js. Within this file, there are two variables that we want to access in th ...

What is the process for moving an ISO date from one system to

Need help with converting ISO date format? Error: Time value is not valid updateDate = e => { let inputDate = e.target.value const parts = inputDate.split('/') const rearranged = [parts[1], parts[0], parts[2]] const newDate ...

Angular Chart.js encountering an issue with data retrieved from a .json file

I am currently working on displaying data in a chart using the chart.js library with Angular. The main issue I am facing involves DeepPartialObjects related to problems with the y and x axes in the chart options. As someone new to both Angular and Chart.js ...

Headers error encountered during sending request

When making a request with this method, an error labeled as "[ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client" occurs. I recently started learning about express and might have made some progress. Can you please help me identif ...

What is the best way to handle empty inputs in a class?

I am a novice web developer working on my first application, a small CRUD project. Here is the code I have so far: <template> <CRow> <CCol col="12"> <CCard no-header> <CCardBody> <h3& ...

Angular: Troubleshooting blank pages in HTML - What's causing it?

This is the content of my heroes component: <!--The content below is only a placeholder and can be replaced.--> <div style="text-align:center"> <h1> <h2>{{hero.name}} Details</h2> <div><s ...

What causes the input field to lose focus in React after typing a character?

Currently utilizing React Mui for components and encountering no errors in either the Chrome inspector or terminal. How can this be resolved? No error notifications are being displayed by eslint or Chrome Inspector. The form submission functions correctl ...

Transforming a flow type React component into JSX - React protocol

I have been searching for a tooltip component that is accessible in React and stumbled upon React Tooltip. It is originally written in flow, but I am using jsx in my project. I am trying to convert the syntax to jsx, but I'm facing difficulties with t ...

GetServerSideProps function yielding varied prop values

I'm currently exploring NextJS and delving into SSR. I've been struggling to grasp the functionality of getServerSideProps(). It seems that it should replace useState in order to be rendered on the backend, but I'm receiving different props ...

Do JavaScript have dictionary functionality similar to Python?

I am trying to create a dictionary in JavaScript that looks something like this: I can't recall the exact syntax, but it was similar to: states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ } Does JavaScript support this ty ...

Ways to combine multiple then() promises into a single one

I have a section of code where I am using multiple then() methods. I am looking to streamline this and have it only utilize one then(). Is there a way to achieve this? getGreeting = () => { fetch(url) .then((response) => response.json()) ...

Accessing JavaScript variables within Selenium

Currently utilizing Selenium Webdriver 2.0 to test an HTML page that incorporates an x.js file. Within x.js, the variable "price" is defined based on data entered from the HTML form and various Javascript calculations. In the HTML, the correct price valu ...

Struggling with displaying Firebase data in React

I am facing an issue with rendering data fetched from Firebase onto the screen. The problem arises when I attempt to call the function that retrieves data from the database inside the componentDidMount() lifecycle method. Surprisingly, the function does no ...

What is the process of transferring information from one window to another window?

Is there a way to transfer data between two windows? In my parent window, I have a button that redirects to another page with a success button. When the success button is clicked on the child window, I want to display "success" text on the parent window. ...

In the context of React Typescript, the term 'Component' is being mistakenly used as a type when it actually refers to a value. Perhaps you intended to use 'typeof Component' instead?

Looking to create a routes array and apply it to useRoutes in react-router@6. I am currently using TypeScript and Vite. However, I encountered an error when attempting to assign my component to the 'element' key. type HelloWorld = /unresolved/ ...

Leveraging both Vuex and an Event Bus in your Vue application

For some time now, I've been pondering over this question that has been lingering in my mind. My current Vue application is quite complex, with a significant number of components that need to communicate effectively. To achieve this, I have implemente ...

Striving to implement a dynamic dropdown menu using React's <select> element and rendering users from an array as selectable options

I am currently working on a project to develop an application that allows users to be added to a MongoDb database and have their names displayed in a dropdown menu. While creating the form, I encountered two issues - one related to the closing tag error a ...

Scroll-triggered animation of SVG paths in React

While achieving this in vanilla Javascript is relatively simple (check out this for an example), I'm encountering difficulties implementing it in React, especially with a library like Framer Motion for animations. Framer Motion's useViewPortScro ...