问题描述: 在使用Apollo和Angular时,变量的突变没有起作用。
解决方法:
import { Apollo } from 'apollo-angular';
import { YOUR_MUTATION } from '../graphql/mutations';
import { YOUR_QUERY } from '../graphql/queries';
@Component({
// ...
})
export class YourComponent {
constructor(private apollo: Apollo) {}
updateData(newVariableValue: any) {
// 使用Apollo的mutate方法进行变量的突变
this.apollo.mutate({
mutation: YOUR_MUTATION,
variables: {
newVariable: newVariableValue,
},
// 成功回调中重新获取数据
refetchQueries: [{ query: YOUR_QUERY }],
}).subscribe(() => {
// 变量的突变成功
}, error => {
// 变量的突变失败
});
}
}
import { Apollo } from 'apollo-angular';
import { YOUR_QUERY } from '../graphql/queries';
@Component({
// ...
})
export class YourComponent {
querySubscription: any;
constructor(private apollo: Apollo) {}
ngOnInit() {
// 监听变量的变化
this.querySubscription = this.apollo.watchQuery({
query: YOUR_QUERY,
variables: {
yourVariable: initialVariableValue,
},
}).valueChanges.subscribe(result => {
// 获取更新后的数据
const newData = result.data;
// 在此更新组件中的变量
});
}
ngOnDestroy() {
// 取消监听
this.querySubscription.unsubscribe();
}
}
请注意,上述示例中的YOUR_MUTATION、YOUR_QUERY和YOUR_VARIABLE是示例代码,你应该使用自己的实际代码来替代它们。另外,确保在Apollo模块中正确配置了GraphQL服务端的URL和其他必要的设置。