代码之家  ›  专栏  ›  技术社区  ›  Martijn van den Bergh

使用Apollo客户机for graphql时如何在watchquery中使用loading属性

  •  13
  • Martijn van den Bergh  · 技术社区  · 7 年前

    所以当我从我的查询中得到响应时,我可以看到有一个加载属性。但我不明白他们为什么要传下去。因为当您得到响应时,这意味着加载已经完成,因此加载总是错误的。

    是否有一种方法可以使用此加载属性,以便在调用仍在加载时显示加载图标?

    我在角度2环境中有以下代码:

    public apolloQuery = gql`
        query {
            apolloQuery 
        }`;
    
    const sub = this.apollo.watchQuery<QueryResponse>({
        query: this.apolloQuery 
    }).subscribe(data => {
        console.log(data);
        sub.unsubscribe();
    });
    

    数据对象的日志包含了我所说的加载属性,这总是错误的。

    我知道我可以创建自己的布尔属性并通过这种方式进行检查,但我只是想知道是否可以使用Apollo提供的内置加载属性?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Rubén Soler    7 年前

    您的订阅具有 loading 参数:

    import { Component, OnInit } from '@angular/core';
    import { Apollo } from 'apollo-angular';
    import gql from 'graphql-tag';
    
    // We use the gql tag to parse our query string into a query document
    const CurrentUserForProfile = gql`
      query CurrentUserForProfile {
        currentUser {
      login
      avatar_url
    }
      }
    `;
    
    @Component({ ... })
    class ProfileComponent implements OnInit, OnDestroy {
      loading: boolean;
      currentUser: any;
    
      private querySubscription: Subscription;
    
      constructor(private apollo: Apollo) {}
    
      ngOnInit() {
        this.querySubscription = this.apollo.watchQuery<any>({
          query: CurrentUserForProfile
        })
          .valueChanges
          .subscribe(({ data, loading }) => {
            this.loading = loading;
            this.currentUser = data.currentUser;
          });
      }
    
      ngOnDestroy() {
        this.querySubscription.unsubscribe();
      }
    }
    

    https://www.apollographql.com/docs/angular/basics/queries.html

    推荐文章