Error occurs when attempting to instantiate a class with parameters that do not match any available constructor signatures

I am attempting to encapsulate each instance of router.navigateByUrl within a class function, with the intention of calling that function in the appropriate context. However, I am encountering an error that states 'Supplied parameters do not match any signature of call target'. Despite consulting various resources on SO, none have provided a solution to my specific issue.

commonRouter.ts

 // Encapsulating navigation to the home route within homePage function
 // This allows for calling homePage instead of directly calling 
 //this.router.navigateByUrl('/home');

import {Router} from '@angular/router';
export class RouterComponent{
  router:any;
  constructor(private rt:Router){
    this.router=rt;
  }
  homePage(){
    this.router.navigateByUrl('/home');
  }

}

someComponent.ts

// Importing the newly created TypeScript file
import {RouterComponent} from './../../app-routing-component';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
  private ms:MainService= new MainService();
  //Instantiating RouterComponent
  private rt:RouterComponent = new RouterComponent(); // Error occurs on this line
  constructor(private fb:FormBuilder) {}
  someMethod(){
    rt.homePage() // Calling homePage
   }
   //... rest of code
}

app-routing.module.ts

// Module containing all route paths and components
import {NgModule} from "@angular/core";
import {RouterModule, Routes} from "@angular/router";
import {HomeComponent} from "./home/home/home.component";

const routes: Routes = [
  {
    path: 'login', component: LoginComponent,

  }, {
    path: 'home', component: HomeComponent,
    children: [{
      path: "account",
      component: AccountsComponent
    },{

    path: '**',
    component: PageNotFoundComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

Answer №1

Your RouterComponent necessitates a Router argument. Router is considered an injectable element, so Angular will be able to resolve it if it knows how to handle your RouterComponent class.

The best approach would be to annotate your class as Injectable and inject the value within the Angular component. For example:

import { Injectable } from '@angular/core';    
import { Router } from '@angular/router';

@Injectable()
export class RouterService {
  constructor(private router: Router) { }

  homePage(){
    this.router.navigateByUrl('/home');
  }
};

Be sure to register it in your module or add it to the providers field in the Component decorator and then import it into your components.

import { Component } from '@angular/core';
import { RouterService } from '...';

@Component({ ... })
export class LoginComponent {
  constructor(private router: RouterService) { }

  toHomePage() {
    this.router.homePage();
  }
};

Since it is considered Injectable, Angular will have no trouble resolving the parameters.

The way you name your RouterComponent class might give the impression to others that it is decorated as an Angular component, when in reality you are using it as a service.

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

What is the best way to create a more compact Select component in React?

Working on React's Select component has been quite the challenge for me. I'm in the process of creating a simple dropdown button, also known as a ComboBox, similar to what can be seen on GitHub Insights: https://i.stack.imgur.com/J9Bcd.png Belo ...

What is the process for passing input values to a dynamic Angular component?

https://i.sstatic.net/hghse.png My goal is to develop a dynamic filtering system where users can specify multiple attributes and their corresponding values to filter a list of components. The dynamically added component includes two dropdown menus: one fo ...

What changes can I make to this jquery code to utilize a background image instead of a background color?

Can someone help me modify this snippet to set a background-image instead of changing the background color? <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("#button_layer").hide(); $("#im ...

Discover the element's selector for the event that was triggered using jQuery

In the process of creating a lightweight real-time application, we are utilizing jQuery's event system to facilitate communication between modules. Any changes made in the DOM that affect elements outside the module are achieved through triggering eve ...

Angular JS Changing Values in a Dynamic List

Creating Dynamic HTML with Angular Directives I'm working on code that generates HTML dynamically and includes Angular directives. Since these directives are late-bound, I need to ensure they execute and generate their respective template contents. I ...

Implementing Alloy-Script/Javascript in dynamically loaded JSP files

I have been loading various JSPs dynamically using an Ajax call, but after the JSP is loaded, none of the JavaScript inside seems to be working. I suspect this is because the script has not been parsed yet. To address this issue, I came across the "aui-pa ...

Plugin for controlling volume with a reverse slider functionality

I have been customizing the range slider plugin found at to work vertically instead of horizontally for a volume control. I have successfully arranged it to position the fill and handle in the correct reverse order. For instance, if the value is set to 7 ...

Discovering the values within a separate JSON object

I have a collection of json objects that include information about different languages and user details. Languages User Details The user details contain a field for languages, which can have multiple values. Below is a sample json: $scope.languages = ...

Guide to verifying the property value following mocking a function: Dealing with Assertion Errors in Mocha

Based on a recommendation from a discussion on this link, I decided to mock the readFileSync function and then mocked my outer function. Now, my goal is to verify whether the variable's value has been set as expected. file.js const fs1 = require ...

What is the best way to split an AJAX response into different variables and effectively retrieve each one of them?

When using AJAX to fetch data from a database and display it in a text box, most examples found online only show how to display the AJAX response in one text box. But what if we need to separate multiple PHP variables retrieved from the AJAX response and d ...

Angular directive for resizing C3 charts

I've recently implemented a basic donut chart using C3, which I've enclosed in a directive and everything is functioning smoothly. Below is the code for my directive: angular.module('dashboardApp').directive('donutChart', fu ...

Error: The function .default.auth.signout is not recognized in the REACT and Firebase environment

I've come across several error questions on StackOverflow, but most remain unanswered. The ones that are answered don't seem to solve my issue. I need help debugging this particular error. In my REACT project using Firebase, I'm working on ...

What is the best way to compress JSON responses?

During a recent interview, I encountered a question that asked how to minify a JSON response. Here is the sample JSON response: { "name": "sample name", "product": "sample product", "address": "sample address" } I am unsure of how to minify this J ...

Troubleshooting Problem with Uploading Several Photos to Firebase Storage

I need assistance with uploading multiple photos to Firebase Storage. Despite my efforts, it seems that the original upload keeps getting overwritten and the folder with the venueID property is not being created. Can someone provide some guidance on this i ...

Error message: ParseError: Received an unexpected character '<' while running tests using AVA

Initially encountering an issue within the project built on nuxt, I attempted to resolve it by creating a new project using vue-cli and re-installing AVA via npm. However, this did not have any effect on the problem at hand. Upon researching, I came across ...

Utilizing BEM Class Names in React

How can I utilize the Post component in a way that assigns unique classes to new and old posts following BEM recommendations? Assign a unique className to every element Avoid cascading dependencies like (.posts-new post or .posts-old post) Each component ...

Creating a dynamic configuration for Highchart within an Angular UI grid with the help of AngularJS utilizing the valuable Highcharts NG tool developed by pablo

In my controller, I have created the following code to set up an angular ui-grid - function fetchData() { $scope.data = []; $scope.columns = []; $scope.gridOptions = { data: 'data', useExternalSorting: true, ...

I've exhausted all my knowledge but still unable to get Tailwind to work

I've been troubleshooting Tailwind for the past 6 hours. Managed to set it up in a simpler Nextjs/React/Typescript project, but struggling to get it working in this larger codebase. I'm sure I'm missing something obvious, but I'm at a ...

Unable to fetch data from Array using an identifier in Angular 4

My goal is to fetch an object from an array by its id using the getItem() method. import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; impor ...

Issue encountered while trying to determine the Angular version due to errors in the development packages

My ng command is displaying the following version details: Angular CLI: 10.2.0 Node: 12.16.3 OS: win32 x64 Angular: <error> ... animations, cdk, common, compiler, compiler-cli, core, forms ... language-service, material, platform-browser ... platfor ...