0

I am in the process of making an Angular library that includes auth/graphql related code that all our apps require.

Issue is, I store the uri in an Angular environment variable, which do not exist in an Angular libraries.

Performing an ng add apollo-angular generates the following module:

graphql.module.ts (removed imports for clarity):

const uri = ''; // <-- add the URL of the GraphQL server here
export function createApollo(httpLink: HttpLink) {
  return {
    link: httpLink.create({uri}),
    cache: new InMemoryCache(),
  };
}

@NgModule({
  exports: [ApolloModule, HttpLinkModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink],
    },
  ],
})
export class GraphQLModule {}

Notice the uri, which creates a dependency on this module which should be injected.

In my apps app.module.ts, I created a provider which grabs the environment:

providers: [
    {
      provide: 'envVars', useValue: environment
    }
  ]

Which I typically inject via the constructor like so:

constructor(@Inject('envVars') private envVars: any) {}

I've tried many ways to inject this uri to no avail! Suggestions?

Vippy
  • 1,356
  • 3
  • 20
  • 30

1 Answers1

0

I found a solution to my problem found at this StackOverflow post:

https://stackoverflow.com/a/46791075/1207856

However I tweaked mine for my unique situation.

First in AppModule app.module.ts, provide the environment using the forRoot() static method:

GraphQLModule.forRoot(environment)

Second, in your libraries module, you can set that environment to a static member of your class, as such:

export class GraphQLModule {
  public static envVars: any

  public static forRoot(environment: any): ModuleWithProviders {
    // this is to provide to this module non-class section
    this.envVars = environment

    // this is provide to children
    return {
      ngModule: GraphQLModule,
      providers: [
        {
            provide: 'envVars', 
            useValue: environment
        }
      ]
    }
  }
}

Now I can use it statically in this actual module itself or via @Inject in any child component or module that uses this module.

So in this actual module I can do this:

GraphQLModule.envVars.gatewayUri

or in another class's constructor, I can do this:

constructor(@Inject('envVars') private envVars: any) {}

Enjoy!

Vippy
  • 1,356
  • 3
  • 20
  • 30