为了让我的角组件能够通过简单的查询( GraphQL )从阿波罗的GraphQL服务器检索数据,我已经挣扎了好几个小时。我使用阿波罗-角4.1.0和@阿波罗/客户3.0.0,甚至尝试了@graphql-编码/类型记录-阿波罗角
这是我的应用程序模块:
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { GraphQLModule } from './graphql.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AppMaterialModule } from './app.material.module';
import { DummyComponent } from './components/dummy/dummy.component';
import { PingGQLService } from './services/ping.service';
@NgModule({
declarations: [
AppComponent,
DummyComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
AppMaterialModule,
GraphQLModule,
HttpClientModule,
],
providers: [PingGQLService],
bootstrap: [AppComponent],
})
export class AppModule {}这是我的GraphQLModule:
import { HttpClientModule, HttpHeaders } from '@angular/common/http';
import { NgModule } from '@angular/core';
import {
ApolloClientOptions,
ApolloLink,
InMemoryCache,
} from '@apollo/client/core';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { PingGQLService } from './services/ping.service';
const uri = 'http://localhost:3000'; // <-- add the URL of the GraphQL server here
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
const http = httpLink.create({ uri, withCredentials: true });
const contentType = setContext((operation, context) => ({
headers: new HttpHeaders().set('Content-Type', 'application/json'),
}));
const proto = setContext((operation, context) => ({
headers: new HttpHeaders().set('x-forwarded-proto', 'https'),
}));
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
if (networkError) console.log(`[Network error]: ${networkError}`);
});
return {
link: ApolloLink.from([contentType, proto, errorLink, http]),
cache: new InMemoryCache(),
};
}
@NgModule({
exports: [ApolloModule, HttpClientModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
},
PingGQLService,
],
})
export class GraphQLModule {}这是我的PingGQLService:
import { Injectable } from '@angular/core';
import { gql, Query } from 'apollo-angular';
export interface Response {
pong: string;
}
@Injectable({
providedIn: 'root',
})
export class PingGQLService extends Query<Response> {
override document = gql`
query Ping {
ping
}
`;
}这是我的虚拟组件:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { PingGQLService } from 'src/app/services/ping.service';
@Component({
selector: 'app-dummy',
templateUrl: './dummy.component.html',
styleUrls: ['./dummy.component.css'],
})
export class DummyComponent implements OnInit {
ping!: Observable<string>;
pingJson!: string;
constructor(private pingGQL: PingGQLService) {}
ngOnInit() {
this.ping = this.pingGQL.watch().valueChanges.pipe(
map((result) => {
console.log(result.data);
return result.data.pong;
})
);
this.pingJson = JSON.stringify(this.ping);
}
}这是HTML:
<p>dummy works!</p>
<h1>Account:</h1>
<ul>
<li>{{ pingJson }}</li>
<li>{{ ping }}</li>
</ul>我不知道我的代码出了什么问题,可能与CORS有关,但这是我的GraphQL服务器配置:
import "module-alias/register";
import "reflect-metadata";
import express from "express";
import session from "express-session";
import { startServer } from "@/app";
import { HOST, NODE_ENV, PORT } from "@/configs/index";
import { loadConsumers } from "@/mq/consumers";
declare module "express-session" {
interface Session {
token: string | undefined;
}
}
loadConsumers()
.then(() => {
console.log("MQ consumers loaded");
})
.catch((error) => {
console.error("MQ consumers failed to load", error);
});
const app = express();
app.use(
session({
secret: "secret",
resave: false,
saveUninitialized: false,
cookie: { secure: true, sameSite: "none", maxAge: 2 * 60 * 60 * 1000 },
})
);
app.set("trust proxy", 1);
// Setup graphql
startServer()
.then((server) => {
server.applyMiddleware({
app,
path: "/graphql",
cors: {
credentials: true,
origin: [
"https://studio.apollographql.com",
"http://localhost:3000/graphql",
"http://localhost:4200",
"http://localhost:4200/",
"*",
],
},
});
app.listen(PORT, () => {
console.log(
`Server running on ${NODE_ENV} mode at http://${HOST}:${PORT}/graphql`
);
});
})
.catch((err) => {
console.error("Error starting server", err);
});我希望HTML能给我这样的答案:
{
"data": {
"ping": "pong"
}
}甚至是一个错误,但没有什么比这更能显示出:
我没有任何新的日志在我的控制台,所以我不知道后面发生了什么,甚至我的头被发送。
更新:--我已经简化了GraphQLModule,并根据这个例子更改了DummyComponent,现在它不再将服务用作外部服务,仍然无法工作。这些变化如下:
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { ApolloClientOptions, InMemoryCache } from '@apollo/client/core';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
const uri = 'http://localhost:3000/graphql';
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
const http = httpLink.create({ uri });
return {
link: http,
cache: new InMemoryCache(),
};
}
@NgModule({
exports: [ApolloModule, HttpClientModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
},
],
})
export class GraphQLModule {}import { Component, OnInit } from '@angular/core';
import { Apollo, gql } from 'apollo-angular';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export type Query = {
ping: string;
};
@Component({
selector: 'app-dummy',
templateUrl: './dummy.component.html',
styleUrls: ['./dummy.component.css'],
})
export class DummyComponent implements OnInit {
ping!: Observable<string>;
pingJson!: string;
constructor(private apollo: Apollo) {}
ngOnInit() {
this.ping = this.apollo
.watchQuery<Query>({
query: gql`
query Ping {
ping
}
`,
})
.valueChanges.pipe(map((result) => result.data.ping));
this.pingJson = JSON.stringify(this.ping);
}
}发布于 2022-10-23 01:38:19
我不敢相信,但毕竟,解决方案是在HTML模板中使用{{ ping | async }}。
我甚至不知道异步管道在角度上的使用,但它当然给了我20个小时的纯粹压力。
此外,由于@puelo的评论,我离开了我的GraphQLModule清洁剂,它完美地工作了。
https://stackoverflow.com/questions/74166658
复制相似问题