Angular-Apollo:尚未定义客户端 [英] Angular - Apollo: Client has not been defined yet

查看:134
本文介绍了Angular-Apollo:尚未定义客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为graphql使用apollo客户端.我在要导入AppModule的AppApolloModule中设置了客户端.我正在服务中查询,该服务也直接在AppModule中导入.尽管该服务在AppApolloModule运行之前运行,因此在进行查询时未初始化apollo,但出现此错误

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

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

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

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.

如何使apollo在服务或与此相关的任何服务之前以有效且标准的方式运行?

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

推荐答案

这将很好地解决该问题:

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

这篇关于Angular-Apollo:尚未定义客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆