【问题标题】:Why parameter query is null in GraphQL Controller when I pass graphql query from Angular?当我从 Angular 传递 graphql 查询时,为什么 GraphQL 控制器中的参数查询为空?
【发布时间】:2018-08-02 18:44:38
【问题描述】:

我正在尝试使用 GraphQL,我正确构建了所有内容,但是当我从 Angular 应用程序参数“查询”在方法中调用图形控制器时为 null,但是当我从 Postman 调用时,一切正常。

另外我使用 Apollo 连接 GraphQl。

查看我的 GraphQl 控制器:

[Route("graphql")]  
    public class GraphQLController : Controller
    {
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] GraphQLQuery query)
        {
            try
            {
                var schema = new Schema { Query = new StarWarsQuery() };

                var result = await new DocumentExecuter().ExecuteAsync(_ =>
                {
                    _.Schema = schema;
                    _.Query = query.Query;

                }).ConfigureAwait(false);

                if (result.Errors?.Count > 0)
                {
                    return BadRequest();
                }

                return Ok(result);
            }
            catch (Exception ex)
            {
                throw new Exception();
            }
        }
    }

这是我的角度代码:

import { Component, OnInit, Query } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';

import gql from 'graphql-tag';
import { Course, CourseList } from './types';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  constructor(
    private apollo: Apollo
  ) { }

  courses: Observable<Course[]>;

  ngOnInit() {

    this.apollo.query({query: gql`query { allCourses {id title author descriptin topic url }}`}).subscribe(console.log);
  }

}

邮递员请求:

{
"query": "query { allCourses {id title author descriptin topic url }}"
}

邮递员的请求一切正常:

但是当我尝试从角度发送时,查询为空:

【问题讨论】:

  • 您找到解决方案了吗?我有完全相同的问题
  • 我记得我从我的项目中删除了 'apollo graphql' 并提出了简单的 http 请求并在参数中添加了查询。如果您有任何问题,我会在这里发布真正的工作简单

标签: angular graphql angular5 apollo apollo-client


【解决方案1】:

以防万一其他人遇到此问题,我找到了解决方案! 如果您导航到 GraphQLQuery 类的定义,请将 public string Variables { get; set; }string 更改为 object,这样它就变成了:

public object Variables { get; set; }

查询将不再为空

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2023-01-26
    • 2018-04-13
    • 2021-06-07
    • 1970-01-01
    • 2018-03-08
    相关资源
    最近更新 更多