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

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

问题描述

我正在为 graphql 使用 apollo 客户端.我在 AppApolloModule 中设置了我在 AppModule 中导入的客户端.我正在在 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")
      }
}

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

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天全站免登陆