【问题标题】:Error: Apollo has been already created错误:Apollo 已经创建
【发布时间】:2018-10-19 02:19:00
【问题描述】:

我是 GraphQL 的新手。

我想做的是在文本输入上的每个 onBlur 事件上调用 GraphQL 服务器。

问题是:

  • 只成功调用一次。
  • 在第二次调用时,我收到此错误:

ERROR Error: Apollo has been already created.

这可能很明显,但我找不到解决方案。

有没有办法在每个连续发生的onBlur 事件上成功地进行新的 graphql 调用?

onBlurZIP(zip) {
    const zipQuery = gql`
      query {
        getAddressByPostalCode(postalCode: "${zip}") {
            country
            city
            street
            streettype
            state
            stateInitials
            quarter
        }
      }
    `;

    const httpLink = createHttpLink({
      uri: environment.endpoint
    });

    const link = setContext((_, { headers }) => {
      return {
        headers: {
          // headers object...
        }
      }
    });

    this._apollo.create({
      link: link.concat(httpLink),
      cache: new InMemoryCache()
    });

    this.querySubscription = this._apollo.watchQuery<any>({
      query: zipQuery,
      variables: { zip },
      fetchPolicy: 'network-only'
    })
    .valueChanges
    .subscribe(
      res => {
        // do stuff...
      },

      err => console.log(err)
    );
  }

HTML:

<input formControlName="zip" (blur)="onBlurZIP($event.target.value)" type="text" class="form-control" name="zip" id="zip" required>

【问题讨论】:

    标签: angular apollo graphql-js apollo-client


    【解决方案1】:

    Apollo 客户端实例必须是单例的。您需要在应用程序中定义一次并使用&lt;ApolloProvider&gt; 将其传递给组件。你可以参考 react-apollo 文档:https://www.apollographql.com/docs/react/essentials/get-started.html

    您的代码抛出错误,因为您在每个 onBlur 事件上都创建了 apollo 客户端实例。

    编辑:

    angular.js中初始化apollo客户端的相关文档:https://www.apollographql.com/docs/angular/basics/setup.html

    【讨论】:

    • 谢谢!在看到您的答案之前,我发现了一点。实际上我正在使用 Angular,并且必须在我的根 AppModule 中创建一个阿波罗实例。不过你的答案是对的!
    • 抱歉给反应相关的答案,我没有检查角度标签。
    • @rbenvenuto 请你给我角度代码的参考。我得到了同样的错误。如何在 AppModule 中创建 apollo 的实例?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 2016-11-09
    • 1970-01-01
    相关资源
    最近更新 更多