0

I'm playing with the Aurelia intro tutorial and changing it to make a rest call from a custom class. In my class I'm getting an 'http is undefined' error with my method calls, so it appears that Aurelia services aren't being injected. Does injecting work if Aurelia isn't loading the class module?

home.js:

import 'bootstrap/css/bootstrap.min.css!';
import 'bootstrap/css/bootstrap-theme.min.css!';
import 'styles/style.css!'
import 'bootstrap';
import {Search} from '../lib/search.js';

export class Home {

  heading = 'Welcome to Aurelia!';
  firstName = 'John';
  lastName = 'Doe';

  activate() {
  }

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  submit() {
    var s = new Search();
    s.fetch()
      .then(results => this.results = results);
  }

}

search.js:

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';

@inject(HttpClient)
export class Search {

  constructor(http) {
    // constructor is called but http is undefined
    http.configure(config => {
      config
        .useStandardConfiguration();
    });

    this.http = http;
  }

  fetch() {
    // ERROR OCCURS HERE
    return this.http.fetch('find')
      .then(response => response.json());
  }

}

Error:

TypeError: http is undefined
John Manko
  • 1,828
  • 27
  • 51

1 Answers1

2

Search has to be injected in Home and better not to use .js when importing

import {Search} from '../lib/search';
@inject(Search)
export class Home {
  constructor(search) {

  }
}

UPD: Here https://stackoverflow.com/a/34796010/3436921 you can find more examples on different ways of using injection

UPD2: Or you can pass HttpClient instance manually to the Search constructor

import {HttpClient} from 'aurelia-fetch-client';
@inject(HttpClient)
export class Home {
 constructor(http) {
   this.http = http;
 }
 ...
 submit() {
  var s = new Search(this.http);
  ...
 }
}
Community
  • 1
  • 1
valichek
  • 1,186
  • 6
  • 9
  • Although this answer solves my error, it doesn't answer my question on why injection of `HttpClient` on the `Search` class doesn't work. Can you explain? – John Manko Feb 03 '16 at 09:29
  • 1
    when you create `new Search()`, injections inside `Search` are not executed, because injection should be parsed by aurelia engine. To get `HttpClient ` inside `Search` just inject it in `Home` and then pass it to Search `new Search(this.http)` – valichek Feb 03 '16 at 10:22