下面是一个使用Angular和GraphQL进行Mutation的示例代码:
npm install apollo-angular graphql
graphql.service.ts
的文件,并添加以下代码:import { Injectable } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { gql } from 'graphql-tag';
@Injectable({
providedIn: 'root'
})
export class GraphqlService {
constructor(private apollo: Apollo) { }
createObject(name: string, description: string): any {
return this.apollo.mutate({
mutation: gql`
mutation CreateObject($name: String!, $description: String!) {
createObject(name: $name, description: $description) {
id
name
description
}
}
`,
variables: {
name,
description
}
});
}
}
object.component.ts
的文件,并添加以下代码:import { Component } from '@angular/core';
import { GraphqlService } from './graphql.service';
@Component({
selector: 'app-object',
template: `
`
})
export class ObjectComponent {
name: string;
description: string;
constructor(private graphqlService: GraphqlService) { }
createObject(): void {
this.graphqlService.createObject(this.name, this.description)
.subscribe(({ data }) => {
console.log('Object created:', data.createObject);
});
}
}
app.module.ts
),并添加以下代码:import { NgModule } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { InMemoryCache } from '@apollo/client/core';
@NgModule({
// ...
})
export class AppModule {
constructor(apollo: Apollo, httpLink: HttpLink) {
apollo.create({
link: httpLink.create({ uri: 'http://localhost:4000/graphql' }),
cache: new InMemoryCache()
});
}
}
这里假设你的GraphQL服务运行在http://localhost:4000/graphql
上。根据你的实际情况进行相应的更改。
这是一个简单的示例,演示了如何使用Angular和GraphQL进行Mutation。你可以根据你的需求进行修改和扩展。