【发布时间】:2018-03-13 07:27:06
【问题描述】:
我有以下示例应用程序布局:
app.module
|
|-- dashboard.module (lazy loaded)
|-- dashboard-routing.module (imported by dashboard.module)
|-- dashboard.service (provided by dashboard.module)
|-- dashboard.component (depends on dashboard.service)
|
|-- notifications.module (lazy loaded)
|-- notifications-routing.module (imported by notifications.module)
|-- notifications.service (provided by notifications.module)
|-- notifications.component (depends on notifications.service)
|
|-- my-notifications-dashboard-widget.component <- this should be added
|
|-- ...
每个模块(dashboard、notifications、...)都在延迟加载。
现在我想添加一些MyNotificationsDashboardWidgetComponent,这取决于notifications.service。然后这个小部件应该被注入到dashboard.service。
只要提供的 WidgetComponent 位于 dashboard.module 内,这样就可以正常工作。但是如果我把组件放在懒加载的notifications.module里面,当然不行。
现在我想知道,如何以一种好的、面向模块的方式解决这个问题。
我的要求:
应该只有一个
notifications.service,notifications.component和my-notifications-dashboard-widget.component应该使用。应该延迟加载大模块(
dashboard、notifications)。dashboard.module不应该对notifications.module和/或my-notifications-dashboard-widget.component有任何了解。
想法:
我想,我需要一些预先加载的模块,其中包含my-notifications-dashboard-widget.component。因此,该组件及其提供者在dashboard.module 被加载之前是已知的。
但是我猜我也必须将notifications.service 放在这个模块中?!
当前(非工作)方法的一些代码sn-ps:
dashboard.service:
@Injectable()
export class DashboardService {
constructor(@Inject(DASHBOARD_WIDGET) widgets) {
// inject all provided widgets
widgets.forEach(w => console.log(w.type));
}
}
notifications.module:
@NgModule({
imports: [ NotificationsRoutingModule ],
declarations: [ NotificationsComponent ],
providers: [
NotificationsService,
// this is currently not working, because of lazy loading
{
provide: DASHBOARD_WIDGET,
useValue: {
type: 'my-notifications'
component: MyNotificationsDashboardWidgetComponent
},
multi: true
}
],
entryComponents: [ MyNotificationsDashboardWidgetComponent ]
})
export class NotificationsModule { }
notifications.component:
@Component({ ... })
export class NotificationsComponent {
constructor(service: NotificationsService) { ... }
}
my-notifications-dashboard-widget.component:
@Component({ ... })
export class MyNotificationsDashboardWidgetComponent {
constructor(service: NotificationsService) { ... }
}
【问题讨论】:
标签: angular angular2-routing lazy-loading angular2-services angular-router