![](/img/trans.png)
[英]How can I add API key to Apollo-Angular to fetch data from mongodb realm GraphQL API
[英]How can I use fragments with apollo-angular
我使用 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。 有人可以幫助我嗎?
在查詢 graphql 服務器時使用帶有apollo-angular的片段
創建一個像這樣的變量
POST_FIELDS = gql`
fragment POST_FIELDS on Post {
_id
title
content
creator {
_id
name
email
}
imageUrl
updatedAt
}
`;
上述查詢的解釋如下 -
現在像這樣在 gql 查詢中使用片段
this._apolloClient.watchQuery<any>({
query: gql`
query FetchPosts($page: Int = 1) { // FetchPosts is the operation name
posts(page: $page) { // posts is the resolver to execute on server
posts { // Required response
...POST_FIELDS // Used the defined fragment
}
totalPosts // // Required response
}
}
${this.POST_FIELDS} // Injected the above defined fragment
`,
variables: {
page: 1,
},
context: {
headers: new HttpHeaders().set("Authorization", this.token), // Passed additional custom header along with the global headers
},
}).valueChanges.subscribe({
next: (result: any) => {
this.posts = result?.data?.posts.posts;
this.loading = result.loading;
this.error = result.error;
console.log('Logging Fetch Posts Query----', this.posts, this.loading, this.error);
}
});
注意:使用上面解釋的確切代碼時,請務必從 gql 模板文字查詢中刪除注釋。
希望這對您或其他人有所幫助。
快樂編碼! 謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.