在使用GraphQl的Apollo客户端时,如何在watchQuery中使用loading属性

时间:2018-05-18 09:56:35

标签: angular graphql apollo-client

所以当我从查询中得到响应时,我可以看到有一个加载属性。但我真的不明白为什么他们会把它传递给他们。因为当你得到响应时,意味着加载完成,因此加载总是错误的。

有没有办法让我可以使用这个加载属性,以便我可以在呼叫仍在加载时显示加载图标?

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

public apolloQuery = gql`
    query {
        apolloQuery 
    }`;

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

来自数据对象的日志包含我正在讨论的加载属性,它总是错误的。

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

3 个答案:

答案 0 :(得分:4)

有可能,您需要设置选项 notifyOnNetworkStatusChange:true ,对此documentation进行了说明,然后使用加载道具:

this.querySubscription = this.apollo.watchQuery<any>({
  query: CurrentUserForProfile
  ,notifyOnNetworkStatusChange: true <-- This will make the trick
})
  .valueChanges
  .subscribe(({ data, loading }) => {
    this.loading = loading; <-- now this will change to false at the start of the request
    this.currentUser = data.currentUser;
  });

答案 1 :(得分:2)

您的订阅包含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

答案 2 :(得分:0)

这是 ApolloClient 3 中的 WatchQueryOptions

export interface WatchQueryOptions<TVariables> extends CoreWatchQueryOptions<TVariables> {
    /**
     * Observable starts with `{ loading: true }`.
     * There's a big chance the next major version will enable that by default.
     *
     * Disabled by default
     */
    useInitialLoading?: boolean;
}

意味着您仍然需要明确告诉您希望收到“正在加载”状态更改标记 (useInitialLoading: true) 的通知,否则您只会得到错误信息。

const variables = {};
return apollo
   .watch(variables, { useInitialLoading: true })
   .valueChanges
   .subscribe(({data, loading})=> console.log(loading)));

注意:如果您仍然遇到问题,请使用 a version greater than the 2.4