抽象类:
export abstract class LanguageChangeAware {
private sub: Subscription;
protected language: string;
protected constructor(protected eventService: EventService) {
this.sub = eventService.getLang().subscribe(lang => {
this.language = lang;
this.load();
});
this.load();
}
protected ngOnDestroy(): void {
this.sub.unsubscribe();
}
protected abstract load();
}
组件NewsPage
实现LanguageChangeAware
抽象类:
export class NewsPage extends LanguageChangeAware {
public news: Array<NewsItem>;
constructor(public newsService: NewsService, protected eventService: EventService) {
super(eventService);
}
protected load() {
console.log('NewsPage - load() - ', this.newsService); // <- undefined
this.newsService.getNewsItemsList().then(data => {
this.news = data;
});
}
}
我的问题是在组件的load()
实现中NewsPage
,注入的依赖NewsService
是未定义的。
用户 Antoine Boisier-Michaud 建议的一种可能的解决方案是在方法内进行订阅ngOnInit
。
更新版本LanguageChangeAware
:
export abstract class LanguageChangeAware implements OnInit, OnDestroy {
private sub: Subscription;
protected language: string;
protected constructor(protected eventService: EventService) {
}
public ngOnInit(): void {
this.sub = this.eventService.getLang().subscribe(lang => {
this.language = lang;
this.load();
});
this.load();
}
public ngOnDestroy(): void {
this.sub.unsubscribe();
}
protected abstract load();
}