"Unable to resolve all parameters ..." with @Optional decorator

I get a strange DI error. This is a piece of auto-generated code from swagger-codegen - I cannot change it. I am trying to implement this service. However, when I run ng build --aot , I get a Can't resolve all parameters... DI error.

I tried to completely remove the toOpional @Optional parameter and it seems to work. So this seems to be a criminal.

My question is: Why am I getting an error message without providing a parameter if it is optional? I am also interested in how I would deal with it if I really wanted to introduce this parameter, since 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 are likely to be what most people can search for. However, I am looking for a solution that will not change the original implementation, as it is automatically generated.

+5
source share
2 answers

If you want to introduce basePath in the MyApi class, you can do this as shown below

Add the path provider to the application providers and use the @Inject('path') parameter decorator to enter it in the MyApi class

 @Injectable() export class MyApi { protected basePath = 'https://localhost/'; public defaultHeaders : Headers = new Headers(); constructor(protected http: Http, @Inject('path') basePath: string) { if (basePath) { this.basePath = basePath; } } } 

Than in the boot file of your application (@NgModule)

 bootstrap('name of your app.component class', [ MyApi, provide('path', { useValue: 'any value which you want to inject'}) ]); 

you can use the @Optional parameter to make the dependency optional.

+2
source

You need to use InjectionToken :

 export const BASE_PATH: InjectionToken<string> = new InjectionToken<string>('basePath'); // note that the string value `basePath` is just a description of the `InjectionToken` // and not actually the base path. 

Benefit of using InjectionToken

Then you need to add the supply object to your providers array of your NgModule :

 @NgModule({ //... providers: [ {provide: BASE_PATH, useValue: '/'} ] }) 

You can then enter this provider into your service using @Inject :

 constructor(protected http: Http, @Inject(BASE_PATH)basePath: string) { if (basePath) { this.basePath = basePath; } } 

And you can add the @Optional decorator if you like it .. but if you add it to your suppliers array, it will always be found

+1
source

Source: https://habr.com/ru/post/1271672/


All Articles