Can't resolve all parameters for Class (?)

Viewed 60

I'm currently trying to create a dynamic menu in angular 9. I'm pretty new to angular and get the following error message for some reason: "ERROR in Can't resolve all parameters for HeadMenuComponent in C:/mypath/head-menu.component.ts: (?, ?, ?)." The code is pretty simple:

import { Component, OnInit, Inject, Injectable } from '@angular/core';

  @Component({
    selector: 'app-head-menu',
    templateUrl: './head-menu.component.html',
    styleUrls: ['./head-menu.component.css']
  })

  export class HeadMenuComponent implements OnInit {
    imageURL: string;
    text: string;
    menuFunction: () => void;

  constructor(@Inject(String)imageURL: string, @Inject(String)text: string, 
              @Inject(Function)functionToAccept: () => void) {
    this.imageURL = imageURL;
    this.text = text;
    this.menuFunction = functionToAccept;
   }


  ngOnInit(): void {
  }

}

The code is compiling and ng serve will work, but I still get the error message. This is especially important to me because the angular-cli command:ng xi18n won't run because of this error.

So my question is:"What am I doing wrong?" Is there another way to pass objects into a constructor? It feels wrong to me to use the angular injection, just to pass a string to the constructor, but I haven't found another way yet.

1 Answers

One way of doing this is to do the following:

export const IMAGE_URL = new InjectionToken<string>('imageUrl');

Then, in app.module (or elsewhere):

{
  provide: IMAGE_URL ,
  useValue: 'www.someurl.com'
}

Or

{
  provide: IMAGE_URL,
  deps: [ConfigService],   //dependencies
  useFactory: (c: ConfigService) => {
      return c.someUrlValue();
  }
}

and then consume:

constructor(@Inject(IMAGE_URL) imageUrl: string) {

}
Related