问题
I am using apollo graphql, and it has a module with a function inside of it.
export function createApollo(httpLink: HttpLink, connectToDevTools: true){
Inside this function you define the url for the graphql endpoint const uri = http://127.0.0.1/graphql
for instance.
I would like to import this url form a service (so that I only have to change the backend server url in one place), but I can not inject the service, for the property stays undefined.
export function createApollo(httpLink: HttpLink, connectToDevTools: true, urlservice: UrlsService) {
const uri = urlservice.graphqlAddress;
Error: Cannot read property 'graphqlAddress' of undefined
I have also tried injecting the service into the modules constructor, but this is even lower down the chain, with the same results.
How do I get an outside property into the function createApollo
?
My service basically looks like this:
export class UrlsService {
...
graphqlAddress = 'http://192.168.2.24:8000/graphql/';
...
}
GraphQLModule providers:
@NgModule({
exports: [ApolloModule, HttpLinkModule],
providers: [
UrlsService,
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
},
],
})
export class GraphQLModule {
}
回答1:
When declaring a factory function that takes parameters, you need to declare these parameters in the dependency setting deps
, in the providers config. (This is explained in the angular doc). So in your example, you need to add UrlsService
@NgModule({
exports: [ApolloModule, HttpLinkModule],
providers: [
UrlsService,
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink, UrlsService],
},
],
})
export class GraphQLModule {
}
Also, the connectDevTools
argument does not look like it's declared properly
export function createApollo(httpLink: HttpLink, connectToDevTools: true, urlservice: UrlsService)
来源:https://stackoverflow.com/questions/52659398/angular-dependency-injection-into-an-export-function