【问题标题】:Apollo-boost caching issueApollo-boost 缓存问题
【发布时间】:2019-02-20 02:34:44
【问题描述】:

我遇到了 apollo 客户端缓存的问题,我不确定我是否理解原因。我正在使用 apollo-boost 构建一个 angular 6 应用程序,一切运行良好。我现在有一个场景,其中我的 graphql 查询需要一个 id(用户的)和一个过滤器字符串(用于过滤后端的记录)。角度组件代码如下:

ngOnInit() {
    this.filter$.subscribe(filterValue => {
        this.route.params.subscribe(this.getAppointments.bind(this, filterValue));
    });
}

getAppointments 函数如下所示:

getAppointments(filter: string, params: {id: string}) {
  this.artistAppointmentBookGQL.watch({artistId: user.artist._id, filter}).valueChanges
    .pipe(
      map(results => {
        // THIS ALWAYS RUNS WHEN THE FILTER CHANGES
        // HOWEVER THE RESULTS ARE ALWAYS THE LAST QUERY RUN
        // IF THE FILTER HAS BEEN RUN BEFORE
        console.log(user.artist._id, filter, results.data.artist.appointmentBook);
        return results.data.artist.appointmentBook;
    }));
}

graphql 查询:

query artistAppointmentBook($artistId: ID!, $filter: String) {
  artist(id: $artistId, appointmentType: $filter) {
  _id
  appointmentBook {
    _id
    created_at
    firstName
    lastName
    date
    price
    stripe {
      charge {
        id
        amount
      }
    }
  }
}

主要问题:

我有 4 种不同的可能过滤器值(全部、未确认、已确认、已付费)。当我使用每个过滤器值运行这些查询时,它按预期工作,并且我从 apollo 服务器获取正确的结果集。但是,一旦我两次运行相同的查询,我只能返回最后一次查询的结果,并且没有进行网络调用,大概是因为它使用的是缓存版本。

缓存不应该基于变量输入吗?当我第一次使用不同的变量运行时,它似乎运行良好,但是一旦一个被复制,我只会得到最后一次调用产生的任何东西。感谢您的帮助!

这个 gif 演示了这个问题:

【问题讨论】:

    标签: angular6 apollo apollo-client apollo-boost


    【解决方案1】:

    解决了我的问题。理所当然,apollo 正在缓存艺术家记录,因为它有一个 _id 和一个类型。过滤器被传递到艺术家查询中,而它本应在 appointmentBook 级别传递。我更新了架构以接受过滤器参数,然后将其传递到那里而不是艺术家查询中。

    原来我有:

    query artistAppointmentBook($artistId: ID!, $filter: String) {
      artist(id: $artistId, appointmentType: $filter) {
      _id
      appointmentBook {
        _id
        created_at
        firstName
        lastName
        date
        price
        stripe {
          charge {
            id
            amount
          }
        }
      }
    }
    

    需要改成:

    query artistAppointmentBook($artistId: ID!, $filter: String) {
      artist(id: $artistId) {
      _id
      appointmentBook(filter: $filter) {
        _id
        created_at
        firstName
        lastName
        date
        price
        stripe {
          charge {
            id
            amount
          }
        }
      }
    }
    

    此次更新后,查询被正确缓存。

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 2020-09-04
      • 2019-12-05
      • 2017-12-08
      • 2019-02-20
      • 2019-02-04
      • 2021-02-26
      • 2017-03-18
      • 2021-01-29
      相关资源
      最近更新 更多