angular - Angular - 常见的 ngOnInit
问题描述
如果我在每个组件中都有
ngOnInit() {
console.log('hello world');
}
如何避免在每个组件中编写该代码?我可以编写一些通用代码来为每个组件触发 onInit,也许在他们的模块中?或者在他们都使用的共享服务中,例如?
我对NavigationStart和NavigationEnd有同样的问题。
谢谢
解决方案
最简单的方法是从基础组件扩展:
@Component({
selector: 'base-component',
template: '',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class BaseComponent implements OnInit {
ngOnInit (): void {
console.log('hello world');
}
}
并extends BaseComponent
在您的子组件中使用,例如:
@Component({
selector: 'child-component',
template: '',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent extends BaseComponent {
// your logic
}
另一种方式:为每个组件使用本地提供者的服务:
@Injectable()
export class ActionService {
constructor(){
console.log('hello world');
}
}
并将它 ( ) 注入providers: [ActionService]
到必须具有此逻辑的组件中,每个组件将具有此服务的单独实例:
@Component({
selector: 'main-page',
templateUrl: './main-page.component.html',
styleUrls: ['./main-page.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [ActionService]
})
export class MainPageComponent {}
至于我:第一个解决方案比每次都提供服务要好得多,但这取决于你:)
推荐阅读
- bash - Bash if else 将 num1 与 num2 或 num3 比较不正确
- java - 如何在 Thymeleaf 中操作队列
- python - VideoWriter OpenCV - 无法在函数 CvVideoWriter_GStreamer::open 中播放管道
- powerbi - 在power bi中计算从一个日期到另一个日期的月数
- php - 将加密方法从php翻译成python
- android - 无法从嵌套的实时数据库中获取要在 recyclerview 中显示的图像
- mysql - 使用转义的 req.body 值数组使用 mysql 插入 SQL 语法错误
- perl - 转义多字节字符
- angular - Angular 中的组件是一种指令?
- database - 涉及大量磁盘 I/O 的大批量处理的并行方法