graphql-code-generator: Undefined Apollo service in Apollo Angular queries/mutations

Describe the bug

When using auto-generated queries or mutations, Mutation.apollo is undefined:

in fesm5 ng.apollo.js:

mutate(variables, options) {
    return this.apollo.use(this.client).mutate(Object.assign({}, options, { variables, mutation: this.document }));
}
ERROR TypeError: Cannot read property 'use' of undefined
    at HomeKeepInTouchMutationGQL.mutate (ng.apollo.js:417)

It’s a new project, I basically copied all the configuration from another project that has virtually the same bootstrap code, so I don’t know what the difference could be, except that the old project uses v0.16.1 and the new one v1.0.6.

If I import Apollo myself in a component, I get an instance of it, and if I manually assign it to the mutation/query, it works fine, like that:

public constructor(
    apollo: Apollo,
    private readonly keepInTouchMutation: HomeKeepInTouchMutationGQL) {

    (keepInTouchMutation as any).apollo = apollo;
}

It looks like there is a problem with inheritance. If I edit the generated file by hand, to add an appropriate constructor in the mutations, it works too:

@Injectable({
    providedIn: "root"
})
export class HomeKeepInTouchMutationGQL extends Apollo.Mutation<
    HomeKeepInTouchMutationMutation,
    HomeKeepInTouchMutationMutationVariables
> {
    document = HomeKeepInTouchMutationDocument;

    public constructor(apollo: Apollo.Apollo) { // this!
        super(apollo);
    }
}

My knowledge of Angular internals stops there, but I’ve already stumbled upon this problem where DI doesn’t works when classes are inherited. Since you rely on this, I thought that this may interest you.

Environment:

All latest versions of codegen libraries, Apollo and Angular.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 15 (3 by maintainers)

Most upvoted comments

Happened to me today using Angular 8 and TS 3.4, in tests only. Setting "target": "es5" in tsconfig.spec.json fixes the issue.

@tgambet Your answer helped me out!

Ok, upgrading to Angular 8 actually did fix this. I was on Angular 7 before.