嗨,我是angular的初学者,我尝试按照教程进行操作。我尝试了一切,但我的依赖项注入无效。当我直接将事件放在事件列表组件上时,它就起作用了。
这是代码。
事件列表组件
import { Component } from '@angular/core';
import { EventService } from './shared/events.service';
@Component({
selector: 'events-list',
template: `<div>
<h1>Upcoming Angular Events</h1>
<hr>
<div class="row">
<div *ngFor="let event of events" class="col-md-5">
<event-thumbnail [event]="event">
</event-thumbnail>
</div>
</div>
</div>
`
})
export class EventsListComponent {
events: any[]
constructor(private eventService: EventService) {
this.events = this.eventService.getEvents()
}
// ngOnInit() {
// this.events = this.eventService.getEvents()
// }
}
事件服务
import { Injectable } from '@angular/core'
@Injectable()
export class EventService {
getEvents() {
return EVENTS
}
}
const EVENTS = [
{
...
}
]
应用模块
import { EventService } from './events/shared/events.service';
@NgModule({
imports: [
BrowserModule
],
declarations: [
RootAppComponent,
EventsListComponent,
NavbarComponent,
EventThumbnailComponent
],
providers: [EventService],
bootstrap: [RootAppComponent]
})
export class AppModule { }
答案 0 :(得分:0)
您能尝试用这种方式重写服务吗?
@Injectable({
providedIn: 'root'
})
export class EventService {
...
}
此后,您可以从AppModule的提供程序列表中删除EventService。试试这个,如果这不能解决您的问题,请随时提出。
编辑:我建议您在this.events = this.eventService.getEvents()
中而不是在构造函数中编写ngOnInit()
。