簡體   English   中英

如何使用帶有阿波羅角的片段

[英]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_TODOSGET_TODO_BY_ID對象中都有重復的代碼。
有沒有辦法減少重復的代碼,以便我可以定義一次TodoAuthor的結構並重用該結構來進行GET_TODOSGET_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
    }
  `;

上述查詢的解釋如下 -

  • POST_FIELDS - 要使用的片段名稱
  • Post - 在您的 graphql 服務器上定義的模式名稱(不在您的前端)
  • Post 的其余內部字段是 post 的模式

現在像這樣在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM