0
我有一個延遲加載模塊,它有一個服務和一個組件。組件找不到來自延遲加載模塊的提供程序
我想在該組件使用的服務,但我得到:
Error: No provider for EventService!
模塊
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]
};
}
}
組件
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));
}
}
服務
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);
}
}
我已經看過這裏的一些帖子,但還沒有能夠從他們那裏得到解決方案。
我知道延遲加載模塊中的提供者是模塊範圍的,而延遲加載模塊有它們自己的依賴樹。
但是必須可以將提供者注入組件,不是嗎?
爲什麼它不適用於forRoot?我認爲在懶惰模塊的情況下,你應該使用forRoot? – user3629892
'forRoot()'用於在根級別配置路由。 'forChildren()'在你根據模塊拆分路由配置時是很好的。通常建議每個模塊都有一個單獨的模塊來配置路由。配置路由的相應模塊將使用'forChildren()'。另一方面,路由'loadChildren'屬性可用於在到達路由時加載模塊異步。 – andreim
因此,在你的情況下,你有'EventModule',你可以有一個單獨的'EventRoutingModule'模塊,它執行'forChildren()'來加載模塊時加載路由配置。 – andreim