I'm trying to inject Renderer2 into my custom service and it's failing with the error as below:
ERROR Error: StaticInjectorError[Renderer2]:
StaticInjectorError[Renderer2]:
NullInjectorError: No provider for Renderer2!
It's a brand new angular app created using cli and my custom service I created is:
import { Injectable, Renderer2 } from '@angular/core';
@Injectable()
export class FontsService {
constructor(private renderer: Renderer2) {
console.log(this.renderer);
}
getFonts() {
return 'Ubuntu';
}
}
And app.module is very simply just providing the newly created service:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FontsService } from './fonts.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [FontsService],
bootstrap: [AppComponent]
})
export class AppModule { }
Any help please?
Thank you.
There is the way which Angular using internally in webworkers, for example.
I've solved the problem with the code below:
import { Renderer2, RendererFactory2 } from '@angular/core';
@Injectable()
class Service {
private renderer: Renderer2;
constructor(rendererFactory: RendererFactory2) {
this.renderer = rendererFactory.createRenderer(null, null);
}
}
Parameters of RendererFactory2.createRenderer method are:
hostElement with type anytype with type RendererType2|nullYou can see that (null, null) parameters are here:
https://github.com/angular/angular/blob/e3140ae888ac4037a5f119efaec7b1eaf8726286/packages/core/src/render/api.ts#L129
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With