How to create Ember Service that fetches data from Apollo GraphQL Server

How to create Ember Service that fetches data from Apollo GraphQL Server


0

I successfully fetched data from Apollo GraphQL Server in Amber route using ember-apollo-client. I tried the same approach to have a service fetching data but I’m getting Uncaught TypeError: this.apollo.query is not a function from app/services/nav-categories.js.

Minimal Working Example

Start a new app using

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

Configure Apollo end point in config/environment.js:

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

    apollo: {
      apiURL: 'https://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}}

1


Load 5 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *