Angular - Apollo:客户尚未定义

时间:2018-03-13 13:39:18

标签: javascript angular graphql apollo graphql-js

我正在使用apollo客户端进行graphql。我在AppApolloModule中设置了我在AppModule中导入的客户端。我在一个也在AppModule中导入的服务中进行查询。虽然该服务在AppApolloModule运行之前运行,因此在进行查询时未初始化apollo并且我收到此错误

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()
        })
    }

}

应用模块

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

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

我没有获得两个控制台app模块和apollo模块,因为该服务首先运行,它没有找到任何已初始化的apollo应用程序,从而破坏了代码。

如何以高效和标准的方式在服务或任何服务之前运行apollo?

3 个答案:

答案 0 :(得分:2)

这将很好地解决该问题:

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 {}

答案 1 :(得分:0)

@wendellmva的回答对我不起作用。此仓库中建议的解决方案是做了的工作:

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

基本上是将Apollo初始化放在一个单独的共享模块中,并通过forRoot()将其包含在您的主应用程序模块中。

答案 2 :(得分:0)

我遇到了同样的问题,阿波罗的文档帮助了我。转到“ https://www.apollographql.com/docs/angular/basics/setup/”或复制以下内容:

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

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    ApolloModule,
    HttpLinkModule
  ],
  providers: [{
    provide: APOLLO_OPTIONS,
    useFactory: (httpLink: HttpLink) => {
      return {
        cache: new InMemoryCache(),
        link: httpLink.create({
          uri: "https://o5x5jzoo7z.sse.codesandbox.io/graphql"
        })
      }
    },
    deps: [HttpLink]
  }],
})
export class AppModule {}