angular - 当我们在服务中使用 ngOnInit 时?
问题描述
当我们在服务中使用 ngOnInit 时?
例如,我需要在服务中监听 Observer:
this.eventService.subscribe((data) => {
});
将此代码放在构造函数或 ngOnInit 中哪个更好?
解决方案
ngOnInit
是一个角度生命周期钩子。它们仅在组件/指令中可用。在服务中,您不能使用它们。所以需要在构造函数下使用this。
constructor(){
this.eventService.subscribe((data) => {
});
}
推荐阅读
- python - Python字符串操作生成日期格式
- python - pm2在使用python时在日志中显示颜色
- android - 折叠工具栏布局在展开时会在底部导航栏下方创建一个间隙
- plsql - 如何使用 PL/SQL 提取存储在 LONG 列(数据类型)中的数据?
- graphql - OWASP 规则和 Graphql
- django - DsTProductAttributes.product 必须是 DsTProductCompany 实例 Django
- android-studio - Android Studio v31/values-v31.xml 不断生成颜色代码
- c - 在 C 中对 3 个变量进行排序是行不通的
- python - 我正在尝试让我的 discord.py 机器人创建并向用户添加角色但是我不断收到 AttributeError
- javascript - 使用 dijkstra 算法检查两个人在遍历图形时是否会相遇的算法是什么?