Angular - GraphQL - Mutation (大对象)
创始人
2024-10-14 16:31:24
0

下面是一个使用Angular和GraphQL进行Mutation的示例代码:

  1. 首先,安装必要的依赖包:
npm install apollo-angular graphql
  1. 在你的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
      }
    });
  }
}
  1. 在你的组件中使用GraphQL服务。创建一个名为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); }); } }
  1. 在你的模块中配置Apollo客户端。打开你的模块文件(通常是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。你可以根据你的需求进行修改和扩展。

相关内容

热门资讯

重大通报!hhpoker免费透... 重大通报!hhpoker免费透视脚本,pokermaster破解版,黑科技教程(有挂神器);玩家必备...
一分钟教你!wpk官网下载链接... 一分钟教你!wpk官网下载链接,pokeplus脚本,透明挂教程(有挂透明)关于wpk官网下载链接机...
2分钟细说!aapoker透视... 此外,数据分析德州(wepoker透视最简单三个步骤)辅助神器app还具备辅助透视行为开挂功能,通过...
重大通报!wpk透视插件,德普... 重大通报!wpk透视插件,德普之星透视辅助,必胜教程(有挂攻略);亲真的是有正版授权,小编(透视辅助...
攻略讲解!安装不了wepoke... 攻略讲解!安装不了wepoker,wepoker插件功能辅助器,必胜教程(有挂技巧)是一款可以让一直...
专业讨论!wepoker免费透... 专业讨论!wepoker免费透视,pokermaster辅助器,我来教教你(有挂透明)准备好在pok...
分享一款!aapoker透视脚... 分享一款!aapoker透视脚本入口,wepoker有没有透视方法,分享教程(有挂神器);支持多人共...
重大发现!wepoker辅助器... 此外,数据分析德州(aapoker安装包怎么使用)辅助神器app还具备辅助透视行为开挂功能,通过对客...
2024教程!sohoo po... 1、2024教程!sohoo poker辅助器,wepokerplus辅助,解密教程(有挂方法)。2...
玩家必看教程!悦扑克脚本,aa... 玩家必看教程!悦扑克脚本,aapoker插件,新2025版(有挂技巧)1、许多玩家不知道悦扑克脚本辅...