[英]Dependency injection of service not working
Hi i am beginner in angular and i tried to follow a tutorial.嗨,我是 angular 的初学者,我尝试按照教程进行操作。 i tried everything but my dependency injection is not working.
我尝试了一切,但我的依赖注入不起作用。 It is working when i directly put the EVENTS on event-list component.
当我直接将事件放在事件列表组件上时它正在工作。
Here is the code.这是代码。
event-list component事件列表组件
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()
// }
}
event-service事件服务
import { Injectable } from '@angular/core'
@Injectable()
export class EventService {
getEvents() {
return EVENTS
}
}
const EVENTS = [
{
...
}
]
app-module应用模块
import { EventService } from './events/shared/events.service';
@NgModule({
imports: [
BrowserModule
],
declarations: [
RootAppComponent,
EventsListComponent,
NavbarComponent,
EventThumbnailComponent
],
providers: [EventService],
bootstrap: [RootAppComponent]
})
export class AppModule { }
Could you try rewrite your service this way:您能否尝试以这种方式重写您的服务:
@Injectable({
providedIn: 'root'
})
export class EventService {
...
}
After this you can remove EventService from your AppModule's providers list.在此之后,您可以从 AppModule 的提供者列表中删除 EventService。 Try this and if this not solve your problem feel free to ask.
试试这个,如果这不能解决您的问题,请随时询问。 Edit: And I can recommend you to write
this.events = this.eventService.getEvents()
in ngOnInit()
not in constructor.编辑:我可以建议你在 ngOnInit() 中写
this.events = this.eventService.getEvents()
ngOnInit()
而不是在构造函数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.