如何将片段与阿波罗角一起使用
我使用 Angular 13 和 apollo-Angular 3.0.0。 我有进行 GraphQL 查询的代码:
const GET_TODOS = gql`
query GetTodos() {
todos() {
id
title
brief
body
tags
created_at
updated_at
author {
id
nickname
avatar
created_at
updated_at
}
}
}`;
const GET_TODO_BY_ID = gql`
query GetTodosById($id: String!) {
todos(id: $id) {
id
title
brief
body
tags
created_at
updated_at
author {
id
nickname
avatar
created_at
updated_at
}
}
}`;
getTodos(): Observable<any> {
return this.apollo.watchQuery({
query: GET_TODOS,
variables: {},
}).valueChanges;
}
getTodoByID(id: string): Observable<any> {
return this.apollo.watchQuery({
query: GET_TODO_BY_ID,
variables: { id },
}).valueChanges;
}
GET_TODOS
和 GET_TODO_BY_ID
对象中都有重复的代码。
有没有办法减少重复的代码,以便我可以定义一次 Todo
和 Author
的结构,并重用该结构来制作 GET_TODOS
或GET_TODO_BY_ID
查询。
我知道 GraphQL 中的 Fragment,但我不知道如何用 Angular 编写 Fragment。有人可以帮助我吗?
I use Angular 13 and apollo-angular 3.0.0.
I have the codes to make GraphQL query:
const GET_TODOS = gql`
query GetTodos() {
todos() {
id
title
brief
body
tags
created_at
updated_at
author {
id
nickname
avatar
created_at
updated_at
}
}
}`;
const GET_TODO_BY_ID = gql`
query GetTodosById($id: String!) {
todos(id: $id) {
id
title
brief
body
tags
created_at
updated_at
author {
id
nickname
avatar
created_at
updated_at
}
}
}`;
getTodos(): Observable<any> {
return this.apollo.watchQuery({
query: GET_TODOS,
variables: {},
}).valueChanges;
}
getTodoByID(id: string): Observable<any> {
return this.apollo.watchQuery({
query: GET_TODO_BY_ID,
variables: { id },
}).valueChanges;
}
There are duplicated codes in both GET_TODOS
and GET_TODO_BY_ID
object.
Is there a way to reduce the duplicated codes so that I can define the struct of Todo
and Author
once and reuse the struct to make GET_TODOS
or GET_TODO_BY_ID
query.
I know Fragment in GraphQL, but I don't know how can I write the Fragment in angular. Someone can help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要在查询 graphql 服务器时使用带有 apollo-angular 的片段,
请创建一个像这样的变量
上述查询的解释如下 -
现在在 gql 查询中使用片段,如下所示
注意:在使用如上所述的确切代码时,请务必从 gql 模板文字查询中删除注释。
希望这对您或其他人有帮助。
快乐编码!谢谢。
To use fragment with apollo-angular when querying the graphql server
create a variable like this
The explanation for above query is as follow -
Now use the fragment in your gql query like this
Note: Do remove the comments from gql template literal query while using the exact code as explained above.
Hope this help you or somebody else.
Happy Coding! Thanks.