简体   繁体   中英

Angular 6 library root Provider with factory

I'm trying to build a library with a Service that needs a config from the end-user application.

But when I build the library I get this warning:

Warning: Can't resolve all parameters for CacheService in ... This will become an error in Angular v6.x

Here is the code:

@Injectable()
export class CacheService {
  private config: Config;

  constructor(config: Config) {
    this.config = config;
  }
}

@NgModule({

})
export class MyModule {
  static forRoot(config: Config): ModuleWithProviders {
    return {
      ngModule: MyModuleRoot,
      providers: [
        { provide: CacheService, useFactory: cacheServiceFactory, deps: [config] }
      ]
    };
  }
}

export function cacheServiceFactory(config: Config): CacheService {
  return new CacheService(config);
}

When I try to run my main-app with CacheService injected in a constructor, I get AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: StaticInjectorError(AppModule)[CacheService -> [object Object]]:

but I don't want it to be injected but use the factory I've created...

What's wrong with my code ?

Ok here is the solution,

You need to provide the config so it can be injected in the service. That way, there is no need for a factory!

@NgModule({

})
export class MyModule {

  static forRoot(config: Config): ModuleWithProviders {
    return {
      ngModule: MyModuleRoot,
      providers: [
        { provide: Config, useValue: config },
        CacheService
      ]
    };
  }

}

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