Apollo Angular中的直接缓存访问

时间:2017-07-04 21:47:10

标签: angular graphql apollo apollo-client

我有以下服务类:

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部分出了什么问题。

1 个答案:

答案 0 :(得分:0)

此用户在您居住时,您尝试更新Mutation而不是Query

假设你有这个问题:

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
          }
        });
      },
    })
  }
}

查看"Updating the Store"章节,update()文档中包含react-angular功能的部分。这些规则也适用于Angular。