Hi i am beginner in angular and i tried to follow a tutorial. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.