如何将片段与阿波罗角一起使用

发布于 2025-01-09 21:42:12 字数 1251 浏览 0 评论 0原文

我使用 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。有人可以帮助我吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦中的蝴蝶 2025-01-16 21:42:12

要在查询 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 模板文字查询中删除注释。

希望这对您或其他人有帮助。

快乐编码!谢谢。

To use fragment with apollo-angular when querying the graphql server

create a variable like this

POST_FIELDS = gql`
    fragment POST_FIELDS on Post {
      _id
      title
      content
      creator {
        _id
        name
        email
      }
      imageUrl
      updatedAt
    }
  `;

The explanation for above query is as follow -

  • POST_FIELDS - Name of fragment to be used
  • Post - Defined schema name on your graphql server (Not on your frontend)
  • Rest of the inner fields of Post is the schema of post

Now use the fragment in your gql query like this

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);
      }
    });

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文