如何创建从Apollo GraphQL Server获取数据的Ember Service

thtygnil  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(141)

我使用ember-apollo-client成功地从Amber路由中的Apollo GraphQL Server获取数据。我尝试了同样的方法让一个服务获取数据,但是我从app/services/nav-categories.js获取了Uncaught TypeError: this.apollo.query is not a function

最小工作示例

启动新应用程序,使用

$ ember new super-rentals --lang en
$ ember generate service nav-categories

config/environment.js中配置Apollo端点:

module.exports = function (environment) {
  const ENV = {
    ...

    apollo: {
      apiURL: 'http://localhost:4000',
    }
  };

app/gql/queries/allCategories.graphql

query AllCategories {
  categories {
    name
  }
}

app/services/nav-categories.js

import Service from '@ember/service';
import { queryManager } from "ember-apollo-client";
import allCategories from "super-rentals/gql/queries/allCategories.graphql";

export default class NavCategoriesService extends Service {
  constructor() {
    super();
    this.apollo = queryManager();
    this.categories = this.apollo.query({ query: allCategories });
  }
}

app/components/my-header.js

import Component from '@glimmer/component';
import { service } from '@ember/service';

export default class CartContentsComponent extends Component {
  // Will load the service defined in: app/services/nav-categories.js
  @service navCategories;
}

app/components/my-header.hbs

<ul>
{{#each this.navCategories.categories as |category|}}
  <li>{{category.name}}</li>
{{/each}}
</ul>

app/templates/application.hbs

<MyHeader></MyHeader>
{{outlet}}
nkcskrwz

nkcskrwz1#

根据文档,query不返回数组(根据使用情况,它看起来像你所期望的那样)。
query返回promise。
它返回一个promise,该promise使用查询返回的原始POJO数据进行解析。
因此,这意味着您不能将categories字段同步设置到categories列表中。

在.then后设置属性

请记住,您需要自己处理早期破坏保护,以便测试稳定

import { isDestroying, isDestroyed } from '@ember/destroyable';

export default class NavCategoriesService extends Service {
  @tracked categories = [];

  constructor() {
    super();
    this.apollo = queryManager();
    this.apollo.query({ query: allCategories })
      .then(pojoData => {
        // we can't set properties on `this` if `this` is destroyed
        if (isDestroying(this) || isDestroyed(this)) return;
    
        this.categories = pojoData.whatever.results;
      });

  }
}

使用资源实用程序帮助管理promise涉及的状态

Promises有错误、加载等状态,所以正确处理所有这些是很好的。有公用事业

import { trackedFunction } from 'ember-resources/util/function';
import { use, resourceFactory } from 'ember-resources';

function Categories() {
  return trackedFunction(async () => {
    let apollo = queryManager();

    return apollo.query({ query: allCategories });
  });
})

export default class NavCategoriesService extends Service {
  @use categoriesRequest = Categories();

  get isLoading() {
    return this.categoriesRequest.isLoading;
  }

  get categories() {
    return this.categoriesRequset.value ?? [];
  }
}

更多信息:https://github.com/NullVoxPopuli/ember-resources/

相关问题