Angular 9:在构造函数运行之前检查组件模板

问题描述 投票:0回答:1

只是从Angular 8迁移到Angular 9(没有IVY),并发现奇怪的错误,说在getter中未定义注入组件的服务。我调试了一下,发现getter在构造函数之前被调用。

我很好奇这怎么可能。

@Component({
    selector: 'some-component',
    templateUrl: './some-component.pug'
})
export class SomeComponent {
    get someProp () {
        console.log('Getter called', { ...this.someService }); // 'Getter called' {}
        return this.someService.some;
    }

    constructor (private someService: SomeService) { console.log('Constructor called') }

}

// some-component.pug
{{ someProp }}

这将产生一个错误TypeError: Cannot read property 'some' of undefined

angular typescript dependency-injection getter
1个回答
0
投票

我认为问号将解决错误:

return this.someService?.some;

但是您可能要尝试使用诸如ngOnInit之类的生命周期挂钩,因为它是在构造函数之后触发的。

© www.soinside.com 2019 - 2024. All rights reserved.