Angular Ivy (8-beta): How to Inject HttpClient into Component?

To answer my own question: It's possible to fire up the root injector in main.ts. It's not that straight forward as @NgModule, because dependencies have to be provided as well:

in main.ts:

const injector: Injector = Injector.create({
  name: 'root',
  providers: [
    { provide: HttpClient, deps: [ HttpHandler ] },
    { provide: HttpHandler, useValue: new HttpXhrBackend({ build: () => new XMLHttpRequest() }) },
  ]
});

renderComponent(AppComponent, { injector: injector });

I haven't really solved creating a custom element like this though, with the exception of this hack:

class AppComponentCustomElement extends HTMLElement {
  constructor() {
    super();

    renderComponent(AppComponent, { injector: injector });
  }
}

customElements.define('ng-ivy-custom-element', AppComponentCustomElement);

But this way @Inputs etc have to be routed through manually. I'll keep tinkering and update if i find something more usable.

UPDATE: according to https://juristr.com/blog/2019/05/Angular-8-and-the-Future-NGConf-2019-Roundup/#not-every-app-is-a-spa my attempt is not considered a hack, but the right way to achieve this.

Tags:

Angular