I have a lazy-loaded module which has one service and one component.
I would like to use the service in that component but I get:
Error: No provider for EventService!
The module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { EventRoutingModule } from './event-routing.module';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { EventListModule } from './../event-list/event-list.module';
import { ModuleWithProviders } from '@angular/core';
import { EventComponent } from './event.component';
import { EventService } from './event.service';
@NgModule({
imports: [
CommonModule,
FormsModule,
HttpModule,
EventRoutingModule,
EventListModule
],
declarations: [EventComponent]
})
export class EventModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: EventModule,
providers: [EventService]
};
}
}
the component
import { Component, OnInit } from '@angular/core';
import { EventService } from './event.service';
@Component({
templateUrl: './event.component.html',
styleUrls: ['./event.component.scss']
})
export class EventComponent implements OnInit {
private eventService: EventService;
constructor(eventService: EventService) {
this.eventService = eventService;
}
ngOnInit() {
this.eventService.getEvents().subscribe(data => console.log(data), error => console.log(error));
}
}
the service
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AuthHttp } from 'angular2-jwt';
@Injectable()
export class EventService {
private static readonly URL = 'http://localhost:3000/api/events';
constructor(private authHttp: AuthHttp) { }
public getEvents() {
return this.authHttp.get(EventService.URL);
}
}
I have looked at a couple of posts here but havent been able to get a solution from them.
I know providers in lazy-loaded modules are module-scoped and lazy-loaded modules have their own dependency tree.
But it must be possible to inject the provider into the component, mustn't it?