0

我有以下服务等级:

const DeleteUserMutation = gql `
	mutation($user_id: ID!) {
		deleteUser(id: $user_id) {
			id
		}
	}
`;

@Injectable()
export class UserService {
  constructor(private apollo: Apollo) {}

  deleteUser(userId: string) {
    return this.apollo.mutate({
      mutation: DeleteUserMutation,
      variables: {
        user_id: userId
      },
      update: (proxy, mutationResult) => {
        proxy.writeQuery({
          query: DeleteUserMutation,
          data: {
            deleteUser: {
              id: userId,
              __typename: 'User'
            }
          },
          variables: {
            user_id: userId
          }
        });
      },
    })
  }
}

我试图从我的服务器中删除一个用户。突变实际上在服务器上成功运行和执行,但缓存永远不会更新。我不确定我update上面的部分哪里出错了。

4

1 回答 1

0

您正在尝试更新 aMutation而不是 aQuery当此用户居住时。

假设您有以下查询:

query allUsers {
  users: [User]
}

要更新缓存,您需要执行以下操作:

const DeleteUserMutation = gql `
    mutation($user_id: ID!) {
        deleteUser(id: $user_id) {
            id
        }
    }
`;

@Injectable()
export class UserService {
  constructor(private apollo: Apollo) {}

  deleteUser(userId: string) {
    return this.apollo.mutate({
      mutation: DeleteUserMutation,
      variables: {
        user_id: userId
      },
      update: (proxy, { data: { deleteUser } }) => {
        // Get data from `allUsers` query
        const data = proxy.readQuery({
          query: AllUsersQuery
        });

        // Logic to remove an item from an array
        const users = removeUserFromArray(deleteUser.id, data.users);

        // write new array with users to the store
        proxy.writeQuery({
          query: AllUsersQuery,
          data: {
            users
          }
        });
      },
    })
  }
}

看看“更新商店”一章,文档中的update()功能部分。react-angular这些规则也适用于 Angular。

于 2017-07-04T22:18:47.477 回答