2

抽象类:

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();

}
4

1 回答 1

1

构造函数应该用于初始化类成员和依赖注入。如果你有需要做的初始化工作,你应该使用 ngOnInit 方法。当调用 ngOnInit 时,您知道所有的依赖关系都已解决。

export abstract class LanguageChangeAware implements OnInit {

    private sub: Subscription;
    protected language: string;

    constructor(protected eventService: EventService) { }

    protected ngOnInit(): void {
        this.sub = eventService.getLang().subscribe(lang => {
            this.language = lang;
            this.load();
        });

        this.load();
    }

    protected ngOnDestroy(): void {
        this.sub.unsubscribe();
    }

    protected abstract load();
}

如果你想了解更多关于 OnInit 和其他生命周期钩子的信息,你可以阅读Angular 的生命周期文档。

您还可以阅读这篇文章,其中更具体地讨论了何时使用 OnInit 和构造函数。

于 2018-12-01T20:16:16.370 回答