jvandemo / jvandemo/generator-angular2-library

Adding Library configs using `forRoot()` and `InjectionToken`

Open
#219 18 comments 16 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
740
Forks
116
PR merge metrics
No merged PRs in 30d

Description

I'm having trouble adding library configs using `forRoot()` and `InjectionToken`.

When passing in environment variables via `forRoot(config)`, I can access the variables in the `forRoot` method, but they are not injecting into services.

I've added some comments in my sample code to show where things are breaking.

I originally generated my project using `generator-angular2-library@10.1.0`

**app.module.ts (App that uses Library)**
```typescript
@NgModule({
declarations: [AppComponent],
imports: [
CoreModule.forRoot(environment) // {key: 'foobar'}
],
providers: [...],
bootstrap: [AppComponent],
})
export class AppModule { }
```

**index.ts (Library)**
```typescript
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Config, LIB_CONFIG } from './config';
import { FooService } from './foo.service';

@NgModule({
imports: [CommonModule],
providers: [FooService],
})

export class CoreModule {
static forRoot(config: Config): ModuleWithProviders {
console.log(config); // prints: `{key: 'foobar'}`
return {
ngModule: CoreModule,
providers: [
{provide: LIB_CONFIG, useValue: config} // If I hard code `useValue: {key: 'FooBar'}`, instead of using `config` it works... weird.
],
};
}
}
```

**config.ts (Library)**
```typescript
import { InjectionToken } from '@angular/core';

export interface Config {
key?: string;
}

export const LIB_CONFIG = new InjectionToken('LIB_CONFIG');
```

**foo.service.ts (Library)**
```typescript
import { Inject, Injectable } from '@angular/core';

import { Config, LIB_CONFIG } from './config';

@Injectable()
export class FooService {
private key: string;

constructor(
@Inject(WEB_CONFIG) private config: Config,
) {
console.log(config); // prints: `undefined`
this.key = config.key; // can't read property 'key' of undefined
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.