'Cannot access a directive before initialization. Reference error
I have an Angular module with a static function called forRoot() that receives an object as a parameter and a service with a parameter in the constructor called @Inject(FOR_ROOT_CONFIG_DHDIRECTIVES) private config: DirectivesConfig.
This service is called in a directive and when I call this directive in my project, ocurrs an ReferenceError:
ERROR Error: Uncaught (in promise): ReferenceError: Cannot access 'AccessControlDirective' before initialization ReferenceError: Cannot access 'AccessControlDirective' before initialization
I have noticed that if I remove the @Inject parameter from the service, there is no error.
This is my module:
export var FOR_ROOT_CONFIG_DHDIRECTIVES = 'DHDirectivesConfig';
@NgModule({
declarations: [
AccessControlDirective,
],
exports: [
AccessControlDirective,
],
})
export class DhDirectivesModule {
static forRoot(
config: DirectivesConfig
): ModuleWithProviders<DhDirectivesModule> {
return {
ngModule: DhDirectivesModule,
providers: [
DhDirectivesService,
{
provide: FOR_ROOT_CONFIG_DHDIRECTIVES,
useValue: config,
},
],
};
}
}
My Service:
@Injectable({
providedIn: 'root',
})
export class DhDirectivesService {
constructor(
@Inject(FOR_ROOT_CONFIG_DHDIRECTIVES) private config: DirectivesConfig
) {}
exists(id: number | string): void {
// return this.config.actions.some(
// (x) => String(x[this.config.propId]) == String(id)
// );
}
}
My Directive:
@Directive({
selector: '[dhAccessControl]',
})
export class AccessControlDirective implements OnInit {
constructor(
private _directiveService: DhDirectivesService,
private elRef: ElementRef
) {}
ngOnInit(): void {
debugger;
this.elRef.nativeElement.style.display = 'none';
this.check();
}
@Input('dhAccessControlIdOpcion') idOpcion: string = null;
/**
* Verifica si existe la opción si no, remueve el elemento del DOM
*/
checkId() {
// const id: number = parseInt(this.idOpcion);
// const existeAccion = this._directiveService.exists(id);
// if (existeAccion) {
// this.elRef.nativeElement.style.display = 'inline';
// } else {
// this.elRef.nativeElement.remove();
// }
}
}
Also if I remove the DhDirectivesService reference from the directive, there is no reference error
Solution 1:[1]
I answer to myself.
I was doing the dependency injection wrong, so I had to change everything.
In my service I removed the @Inject and left only the name of the object constructor (private config: DirectivesConfig)
and remove @Injectable decorator in my service
In the module I changed the providers in the forRoot method:
providers: [
{
provide: DhDirectivesService,
useClass: DhDirectivesService,
useValue: config,
},
],
And it no longer generates reference errors in the directive where I am using the service
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | IsaĆas Orozco Toledo |
