[英]Dependency injection of service not working
嗨,我是 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 { }
您能否嘗試以這種方式重寫您的服務:
@Injectable({
providedIn: 'root'
})
export class EventService {
...
}
在此之后,您可以從 AppModule 的提供者列表中刪除 EventService。 試試這個,如果這不能解決您的問題,請隨時詢問。 編輯:我可以建議你在 ngOnInit() 中寫this.events = this.eventService.getEvents()
ngOnInit()
而不是在構造函數中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.