1

我在我的项目中使用apollo-angular+ 。subscriptions-transport-ws我有客户端设置来收听用户密码更新或新用户创建事件的订阅。这是它的设置方式

//Apollo Subscription
this.apollo.subscribe({
  query: this.passwordUpdatedSubscription
}).subscribe(({passwordUpdated}:any) => {
  return this.userDataQuery.updateQuery((previousResult) => {
    let userIndex = previousResult.getUsers.findIndex(user => user.name === passwordUpdated.name);
    let updatedUsers;
    if (userIndex === -1) {
      updatedUsers = [].concat(previousResult.getUsers).concat([passwordUpdated]);

    } else {
      updatedUsers = [].concat(previousResult.getUsers.slice(0, userIndex)).concat([passwordUpdated]);
      if (userIndex !== previousResult.getUsers.length - 1) {
        updatedUsers = updatedUsers.concat(previousResult.getUsers.slice(userIndex + 1));
      }

    }
    return Object.assign({}, previousResult, {
      getUsers: updatedUsers,
    });
  });

});

它似乎工作正常,并且可以通知userDataQuery更新。在 中userDataQuery,它以这种方式处理更新

this.userDataQuery = this.apollo.watchQuery({
  query: this.getUsersQuery
}).subscribe(({data}:any) => {
  this.userData = data.getUsers;
  // I have to call detectChanges to tell Angular to re-render the template.
  // is there anyway to avoid doing this?
  //this.ref.detectChanges();

});

userData 确实已成功更新,但是,更改未反映在模板上。我将不得不打电话this.ref.detectChanges();来更新模板。

模板非常简单

<span ng-if="userData">{{userData && userData[0] && userData[0].password}}    </span>

我在代码中遗漏了什么。我认为模板应该自动获取更改?

4

0 回答 0