如果在Angular 7中ngOnInit
方法没有被调用,可能是由于以下几个原因:
OnInit
接口:确保在组件类中实现了OnInit
接口,并导入了OnInit
接口。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
ngOnInit() {
// 在这里初始化组件
}
}
确保在组件模板中使用了正确的选择器,它应该与组件的选择器相匹配。
如果通过路由启动组件,确保在路由配置中使用了正确的组件。
const routes: Routes = [
{ path: 'my-component', component: MyComponentComponent }
];
declarations
数组中:确保在模块的declarations
数组中添加了组件。
@NgModule({
declarations: [
MyComponentComponent
],
...
})
export class AppModule { }
如果以上解决方法都不起作用,可能还有其他问题导致ngOnInit
方法未被调用。在这种情况下,可以进一步检查组件的使用情况,例如组件是否被正常加载,是否存在错误等。