src/app/graphql.module.ts
import { NgModule } from '@angular/core';
import { APOLLO_OPTIONS } from 'apollo-angular';
import { ApolloClientOptions, InMemoryCache, createHttpLink } from '@apollo/client/core';
import { HttpLink } from 'apollo-angular/http';
const uri = 'http://localhost:3000/graphql'; // <-- add the URL of the GraphQL server here
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
return {
link: httpLink.create({ uri }),
cache: new InMemoryCache(),
};
}
@NgModule({
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
},
],
})
export class GraphQLModule {}
这为我们提供了一个硬编码的 URI 变量,它显然不能在本地开发之外工作。我希望能够通过在运行时加载配置文件来更改 URI,而不是构建时间(即不使用 environment.ts)。在使用 Angular 阅读运行时环境配置之后,这似乎是一种合理的方法。
资产/config.json
将在部署时覆盖的本地开发的默认配置
{
"apiUrl": "http://localhost:3000/graphql"
}
src/app/app-config.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface AppConfig {
apiUri: string;
}
@Injectable({
providedIn: 'root'
})
export class AppConfigService {
private appConfig: AppConfig;
private http: HttpClient;
constructor(http: HttpClient) {
this.http = http;
}
async loadAppConfig() {
this.appConfig = await this.http.get('/assets/config.json')
.toPromise() as AppConfig;
}
public get apiUri() {
return this.appConfig.apiUri;
}
}
src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { GraphQLModule } from './graphql.module';
import { AppConfigService } from './app-config.service';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, AppRoutingModule, GraphQLModule, HttpClientModule],
providers: [
{
provide : APP_INITIALIZER,
multi : true,
deps : [AppConfigService],
useFactory : (appConfigService : AppConfigService) => () => appConfigService.loadAppConfig()
}
],
bootstrap: [AppComponent],
})
export class AppModule {}
所以我的问题是,我如何使用AppConfigService
inGraphQLModule
来获取工厂函数apiUrl
并将其设置为uri
工厂createApollo
函数?