1

I have posted a question before on how to configure Aurelia's fetch client and use the configured client in all of my viewModels(Aurelia: configure fetch client) I configure my fetch client in my main.js file. Now i want to use this same configured fetch client in main.js itself. I cant inject an instance of the client because it will be defined after the injection.

import {HttpClient} from 'aurelia-fetch-client';
export function configure(aurelia) {
 this.jsonobj = {
  'operation':'verify'
 };

 aurelia.use
 .standardConfiguration()
 .developmentLogging();

 let container = aurelia.container;
 let http = new HttpClient();
 http.configure(config => {
  config
    .useStandardConfiguration()
    .withInterceptor({
      request(request) {
          request.headers.set('token', window.localStorage.getItem('token'));
        return request;
      }
    });
 });
 container.registerInstance(HttpClient, http);

 aurelia.start().then(
  a => {
   this.http.fetch('dist/components/api.php', {
    credentials: 'include',
    method: 'post',
    body: JSON.stringify(this.jsonobj)
   })
  .then(response =>  response.json())
  .then(data => {
    if (data.error==='true') {
      a.setRoot('login');
    }else {
      a.setRoot('app');
    }
   });
 });
}
Community
  • 1
  • 1
Gilbert Nwaiwu
  • 687
  • 2
  • 13
  • 37
  • I think you have the right code for the most part, just remove the `this.` on the `this.http.fetch('dist/components/api.php', ...` line. – Jeremy Danyow May 12 '16 at 20:06
  • I figured that out a minute after posting but kept the question open to ask: Normally I import http client and inject it into my viewModel. In the code above it takes just a single line to create a http object. Why do we have to inject it(I.e. use Aurelia's DI container) if its so simple to create it ourselves. Also I read a bit on how a DI container works. Do we use DI because only a single copy of the http client exists(I.e. It's a singleton). If so there wont be point in "container.registerInstance(...)" right? – Gilbert Nwaiwu May 14 '16 at 12:57

0 Answers0