Angular中Apollo Client执行GraphQL Mutation报错求助
问题分析与解决方法
核心错误点
- Mutation语法格式错误:你错误地将变量包裹在了
item:的花括号内,GraphQL要求mutation的变量必须在mutation名称后的括号里单独声明,而非嵌套在参数对象中。 - Variables参数格式错误:在
apollo.mutate的variables对象中,键名不需要加$前缀,直接使用变量名即可。 - 字段缺失:你的Angular代码未传递
alter_ego和first_appearance字段,但Postman请求包含这些字段,可能导致后端校验失败。
修正后的代码
Mutation定义
const post_SaveHero = gql` mutation createHero($id: ID!, $publisher: String!, $characters: String!, $superhero: String!, $alter_ego: String!, $first_appearance: String!){ createHero(item: { id: $id, publisher: $publisher, characters: $characters, superhero: $superhero, alter_ego: $alter_ego, first_appearance: $first_appearance }) { superhero id publisher characters alter_ego first_appearance } }`;
addHero方法
addHero(hero: Hero) { return this.apollo.mutate({ mutation: post_SaveHero, variables: { publisher: hero.publisher, characters: hero.characters, superhero: hero.superhero, id: hero.id, alter_ego: hero.alter_ego, first_appearance: hero.first_appearance } }); }
修正说明
- 将所有变量(
$id、$publisher等)移到mutation createHero()的括号内,按照$变量名: 类型!的格式声明。 - 调用
createHero时,通过item: {...}将变量映射到对应字段,确保与后端接收的参数结构一致。 - 移除
variables对象中键名的$前缀,Apollo Client会自动将这些键与mutation中声明的变量绑定。 - 补充
alter_ego和first_appearance字段,保持与Postman请求的参数完整性一致。
内容的提问来源于stack exchange,提问作者azurecosmosdb 2018
相关产品推荐
相关产品推荐

