Angular能否使用带有GraphQL函数装饰的模型?
创始人
2024-10-28 16:01:06
0

首先,需要安装apollo-angular和graphql-tag:

npm install apollo-angular graphql-tag --save

接着,在需要使用GraphQL的组件中引入需要使用的模型和相关的查询或Mutation。例如:

import { Component } from "@angular/core";
import { Apollo } from "apollo-angular";
import gql from "graphql-tag";

// 通过GraphQL查询获取数据
const MY_QUERY = gql`
  query getMyData {
    myData {
      id
      name
    }
  }
`;

@Component({
  selector: "app-my-component",
  template: `
    

{{data.name}}

ID: {{data.id}}

` }) export class MyComponent { myData: any; constructor(private apollo: Apollo) {} ngOnInit() { // 使用Apollo查询获取数据 this.myData = this.apollo.watchQuery({ query: MY_QUERY }).valueChanges.pipe( map(({data}) => data.myData) ); } }

这里使用了Apollo Angular客户端库来发出GraphQL查询并获取数据。需要注意的是,这里的数据模型需要和GraphQL中定义的类型一致。

使用装饰器来定义模型也可以和GraphQL一起使用。例如:

import { Component } from "@angular/core";
import { Apollo } from "apollo-angular";
import gql from "graphql-tag";
import { graphql } from "@decorators/graphql";

// 使用装饰器定义数据模型
@graphql(`
  type MyData {
    id: ID!
    name: String!
  }

  type Query {
    myData: MyData
  }
`)
@Component({
  selector: "app-my-component",
  template: `
    

{{data.name}}

ID: {{data.id}}

` }) export class MyComponent { myData: any; constructor(private apollo: Apollo) {} ngOnInit() { // 使用Apollo查询

相关内容

热门资讯

透视透视!wepoker模拟器... 透视透视!wepoker模拟器哪个好用,wepokerh5破解(详细私人局透视方法)1、让任何用户在...
透视辅助!aapoker真的假... 透视辅助!aapoker真的假的(透视)aapoker公共底牌,大神讲解(有挂黑科技)1)aapok...
透视辅助!aapoker透视脚... 透视辅助!aapoker透视脚本入口(透视)aa poker辅助,wpk教程(有挂规律)1、aapo...
透视免费!wepoker模拟器... 透视免费!wepoker模拟器哪个,wepoker私人局透视插件(详细正规);1、这是跨平台的wep...
透视app!wepoker怎么... 透视app!wepoker怎么破解游戏,wepoker免费透视脚本(详细有脚本)1、首先打开wepo...
透视实锤!aapoker辅助软... 透视实锤!aapoker辅助软件合法吗(透视)aapoker辅助器怎么用,新2025教程(有挂教程)...
透视透视!aa poker辅助... 透视透视!aa poker辅助(透视)aapoker辅助怎么用,专业教程(有挂攻略)1、构建自己的a...
透视ai!wepoker辅助器... 透视ai!wepoker辅助器免费,wepoker怎么看底牌(详细手机插件);一、wepoker怎么...
辅助透视!aapoker怎么控... 辅助透视!aapoker怎么控制牌(透视)aapoker破解侠是真的吗,新2025教程(有挂细节);...
透视规律!wepoker网页版... 透视规律!wepoker网页版透视方法,黑侠破解wepoker(详细新号好一点);1、wepoker...