简体   繁体   中英

Is it possible in angular to inject (say some object) without use import?

I create a angular lib with nx.

And this library is loading by lazy loaded, and I want to configure a variable into this lib.

One way to do that is using forRoot/forChild. but I load this lib module using lazy loading, so if I use this solution I'll integrate this lib inside my app bundle.

Another way is to use @env which map to environment file by tsconfig.base.json , but with this solution is makes the lib depends on the app (which something I don't want to do), and I can see that when I run yarn dep-graph .

Both ways have big significant disadvantage for me.

So I was thinking about using angular tokens.

Defined this token in the app.module:

const FOO = new InjectionToken<string>("foo");
providers: [{ provide: FOO, useValue: { foo: true }, multi: false }]

And in foo.component from the lib, I want to get it:

constructor(@Inject("foo") foo) { console.log({ foo }); }

This code not works. I get error:

NullInjectorError: StaticInjectorError(LibModule)[foo]: 
  StaticInjectorError(Platform: core)[foo]: 
    NullInjectorError: No provider for foo!

So it is possible to inject (say some object) without use import? to get the value from the injector.

In constructor you should use the injection token FOO not the string "foo". So it should be Inject(FOO) foo and FOO should be in best case defined in the lib itself. Then app.module would import only the FOO injection token and provide it. The injection tokens you would like to use in the library are conceptually part of the public interface of the library. The library define what kind of values can be provided from outside of the lib.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM