I am currently working on implementing a service in the following manner:
my-module.module.ts
import { NgModule } from '@angular/core';
import { MyService} from './my-service.service';
@NgModule({
providers: [
{
provide: MyService,
useFactory: () => new MyService(2),
},
],
})
export class MyModule {}
my-service.service.ts
import { Inject, Injectable } from '@angular/core';
@Injectable()
export class MyService {
constructor(
private n: number
) {
console.log(this.n);
}
}
However, I encountered an error message:
Error NG2003: No suitable injection token for parameter 'n' of class 'MyService'. Consider using the @Inject decorator to specify an injection token.
To resolve this issue, a workaround involving Inject('')
was suggested, although it seems unconventional and is not documented in the official documentation:
my-service.service.ts
import { Inject, Injectable } from '@angular/core';
@Injectable()
export class MyService {
constructor(
// Unconventional fix
@Inject('') private n: number
) {
console.log(this.n);
}
}
The Angular version being utilized is 13.3.11