【发布时间】:2019-05-27 07:58:25
【问题描述】:
我正在学习 Pluralsight 的课程,但遇到了问题。我必须提前说明,他们建议在我使用最新版本的同时使用旧版本的 Angular CLI。
跟随涉及依赖注入主题的模块,我收到一个错误(无法解析 EventsListComponent 的所有参数:(?))并且页面拒绝加载。我已经能够解决这个问题,但我认为我的解决方案不是正确的方法,我想知道正确的解决方案应该是什么。
我一直在浏览互联网,但由于某种原因,我必须忽略某些东西,因为仅使用 @Injectable() 装饰器无法使其工作。
我有一个名为 event.service.ts 的文件
@Injectable()
export class EventService {
getEvents() {
return EVENTS;
}
}
其中 EVENTS 是一个 const 数组
const EVENTS = [
{
id: 1,
name: 'Angular Connect',
date: '9/26/2036',
time: '10:00 am',
price: 599.99,
imageUrl: '/assets/images/angularconnect-shield.png',
location: {
address: '1057 DT',
city: 'London',
country: 'England'
}
}
];
我在 app.module.ts 中注册了
@NgModule({
imports: [
BrowserModule
],
declarations: [
EventsAppComponent,
EventsListComponent,
EventThumbnailComponent,
NavBarComponent
],
providers: [EventService],
bootstrap: [EventsAppComponent]
})
根据课程,以下应该将服务注入我的组件(但会导致上述错误)
export class EventsListComponent {
events: any[];
constructor(private eventService: EventService) {
// should be done in the onInit hook but that is the next step in the course
this.events = this.eventService.getEvents();
}
}
我可以通过如下修改代码来解决这个问题
export class EventsListComponent {
events: any[];
eventService: EventService;
constructor(@Inject(EventService) eventService: EventService) {
this.eventService = eventService;
this.events = this.eventService.getEvents();
}
}
我对自己做错了什么感到困惑,因为我在 @Injectable() 装饰器应该处理的解决方案中这样做。
是什么导致了错误以及如何以正确的方式修复它?
【问题讨论】:
-
刚刚做了,但并没有解决它。仍然会导致同样的错误。
标签: angular typescript dependency-injection