Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Apollo: Client has not been defined yet

I'm using apollo client for graphql. I set up the client in AppApolloModule that I'm importing in AppModule. I'm making a query in a service which is also imported right in the AppModule. Although the service runs before the AppApolloModule runs and hence apollo is not initialized when the query is made and I get this error

Error: Client has not been defined yet

AppApolloModule

imports ....

export class AppApolloModule {

    constructor(
        apollo: Apollo,
        httpLink: HttpLink,
        private userService: UserService
    ) {
        console.log("apollo module")
        apollo.create({
            link: httpLink.create({ uri: `${environment.apiBase}/graphql?${this.myService.token}`}),
            cache: new InMemoryCache()
        })
    }

}

App Module

import { AppApolloModule } from './app.apollo.module';
import { MyService } from './services/my.service';

export class AppModule {
      constructor() {
        console.log("app module")
      }
}

I don't get the two consoles app module and apollo module, since the service runs first, it doesn't find any initialized apollo app and thus breaks the code.

How can I make apollo run before the service or any services for that matter in an efficient and standard way?

like image 768
Manzur Khan Avatar asked Mar 13 '18 13:03

Manzur Khan


2 Answers

This will solve the issue nicely:

import {NgModule} from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import {ApolloModule, APOLLO_OPTIONS} from 'apollo-angular';
import {HttpLink, HttpLinkModule} from 'apollo-angular-link-http';
import {InMemoryCache} from 'apollo-cache-inmemory';

export function createApollo(httpLink: HttpLink) {
  return {
    link: httpLink.create({uri: 'https://api.example.com/graphql'}),
    cache: new InMemoryCache(),
  };
}

@NgModule({
  imports: [HttpClientModule, ApolloModule, HttpLinkModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink],
    },
  ],
})
class AppModule {}
like image 145
wendellmva Avatar answered Nov 04 '22 16:11

wendellmva


The answer by @wendellmva didn't work for me. What did work was the solution suggested in this repo:

https://github.com/patricknazar/angular-lazy-loading-apollo-client

which is basically to put Apollo initialization in a separate, shared module, and include it in your main app module with forRoot().

like image 20
AsGoodAsItGets Avatar answered Nov 04 '22 15:11

AsGoodAsItGets