user441058
user441058

Reputation: 1278

Aurelia Typescript DI - instantiate HTTP fetch

I'm having some trouble going past the basic examples in the Aurelia TS skeleton regarding Dependency Injection. The first confusion is where to first instantiate a singleton. For example, in the github sample skeleton they instantiate HttpClient in users.ts:

constructor(public http: HttpClient) {
  http.configure(config => {
    config
     .useStandardConfiguration()
     .withBaseUrl('https://api.github.com/');
    });
}

But I don't want to do this in every class, so I assumed that I would put the code in main.ts since that is run when the app starts. But main.ts doesn't have a constructor and when I try to include @inject(HttpClient) it errors out. Is main.ts the proper place to put this code and if so, how would I do it?

Any ideas?

Upvotes: 2

Views: 304

Answers (2)

Matthew James Davis
Matthew James Davis

Reputation: 12295

You can use the container.get method on the aurelia object to leverage the dependency injection container from within main.ts:

main.ts

import { HttpClient } from 'aurelia-http-client';

export function configure(aurelia) {

    let httpClient = aurelia.container.get(HttpClient);
    http.configure(config => {
      config
        .useStandardConfiguration()
        .withBaseUrl('https://api.github.com/');
      });      
}

Upvotes: 4

user441058
user441058

Reputation: 1278

I found a similar question for JS ( https://github.com/aurelia/dependency-injection/issues/73) and modified it for Typescript and it seems to be working. Here is what I have for anyone who needs it. Not sure if it's the best answer but it is working:

main.ts

bootstrap((aurelia: Aurelia): void => {
  aurelia.use
    .standardConfiguration()
    .developmentLogging();

  var http: HttpClient = new HttpClient();
  http.configure(config => {
  config
    .useStandardConfiguration()
    .withBaseUrl('https://api.github.com/');
  });      
  aurelia.container.registerInstance(HttpClient, http);

  const rootElem = document.body;
  aurelia.start().then(() => aurelia.setRoot('app', rootElem));
  rootElem.setAttribute('aurelia-app', '');
});

Upvotes: 2

Related Questions