I'm trying to inject the npm url node_module into my service in Angular.
I know I can simply just do:
import * as url from 'url';
and can use it in my class as follows:
url.format(); //using it
Although I want to inject it, since I believe I should catch errors sooner, by forcing all my classes to initialize with their dependencies in the constructor.
I know I can use injector Tokens with an interface and useValue to inject simple values.
interface MyInterface {
property: string
}
const JS_PRETEND_TYPING = new InjectionToken<MyInterface>('small_desc');
const MY_VALUE = { a: 123 }
@NgModule({
providers: [ { provide: JS_PRETEND_TYPING, useValue: MY_VALUE } ]
});
Although the url package has it's typing's declared as a module.
In url package:
declare module "url" {
export interface UrlObject {
...
}
So I can't do this because I get an error:
import * as url from 'url';
// ERROR: Cannot use namespace 'url' as a type. const
JS_PRETEND_TYPING_FOR_URL = new InjectionToken<url>('small_desc');
How can I inject the 'url' npm package into my service in Angular?
import * as url from 'url';
class MyService {
constructor(@Inject(JS_PRETEND_TYPING_FOR_URL) private url: url)
}
This happens because
url
is not a type. Classes have types of same names associated with them, but variables, functions and namespaces don't.It should be:
It is generally overkill to use DI for library imports, unless it's known that it will benefit them somehow (testing, etc). In case of
url
this doesn't make sense. It could be tested by spying on its methods. It's very unlikely that there will be a need to swap it with something else by means of DI.