Angular dependency injection into an export function

纵饮孤独 提交于 2021-01-28 10:54:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!