我使用 ember-apollo-client 成功从 Amber 路由中的 Apollo GraphQL Server 获取数据。我尝试了相同的方法来让服务获取数据,但我从
Uncaught TypeError: this.apollo.query is not a function
得到 app/services/nav-categories.js
。
使用
启动新应用程序$ 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}}
根据文档,
query
不返回数组(根据使用情况,它看起来像您所期望的那样)。
query
返回一个承诺。
它返回一个用查询返回的原始 POJO 数据解析的承诺。
因此,这意味着您无法将
categories
字段同步设置到 categories
列表中。
一个选项
请记住,您需要自己处理早期销毁保护, 这样测试就稳定了
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;
});
}
}