I'm getting a strange DI error. This is a piece of auto-generated code from swagger-codegen - I cannot change it. I'm trying to inject this service. However when I run ng build --aot
I get the Can't resolve all parameters...
DI error.
I tried to remove toe @Optional parameter altogether and it seems to work. So this seems to be the culprit.
My question: Why am I getting an error for not providing the parameter if it is optional? I'm also interested how I would go about if I wanted to actually inject this parameter as it is a primitive type.
@Injectable()
export class MyApi {
protected basePath = 'https://localhost/';
public defaultHeaders : Headers = new Headers();
constructor(protected http: Http, @Optional() basePath: string) {
if (basePath) {
this.basePath = basePath;
}
}
}
NOTE: The answers of @Nildari and @PierreDuc will probably be what most people may be looking for. However, I'm looking for a solution which won't change the original implementation as it is auto-generated.
You need to use an
InjectionToken
:The advantage of using an
InjectionToken
Then you need to add an provide object to your
providers
array of yourNgModule
:Then you can inject this provider in your service using
@Inject
:And you can add the
@Optional
decorator if you feel like it.. but if you add it to your providers array, it will always be found