服务的依赖项注入不起作用



嗨,我是angular的初学者,我试着学习教程。我尝试了所有的方法,但是依赖项注入不起作用。当我直接把EVENTS放在事件列表组件上时,它就起作用了。

这是代码。

事件列表组件

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 { }

你能试着用这种方式重写你的服务吗:

@Injectable({
providedIn: 'root'
})
export class EventService {
...
}

之后,您可以从AppModule的提供商列表中删除EventService。试试这个,如果这不能解决你的问题,请随意询问。编辑:我可以建议你在ngOnInit()中写this.events = this.eventService.getEvents(),而不是在构造函数中。

最新更新