javascript - Angular服务在构造函数中调用子方法
问题描述
有没有办法从抽象服务调用子类方法?当我这样做时,该if
语句不会执行,因为onInit
不存在。我不确定为什么它不存在。也许有一种“角度”的方式来做到这一点,而不是在初始化时触发它。或者,也许我只需要在组件中手动调用 onInit。基本上我正在做的是尝试从服务器获取初始应用程序数据。
@Injectable({providedIn:'root'})
export class RootService {
public constructor(httpClient: HttpClient) {
if(typeof this.onInit === 'function') {
this.onInit()
}
}
}
@Injectable({providedIn:'root'})
export class MyService extends RootService {
public onInit() {
// Do stuff
}
}
@Component()
export MyComponent {
public constructor(myService: MyService) {}
}
解决方案
服务没有生命周期事件。但是,组件具有生命周期挂钩,例如:
- ngOnChanges()
- ngOnInit()
- ngDoCheck()
- ...
因此,您可以在组件初始化时加载数据。如果是,那么只需使用ngOnInit
:
import { Component, OnInit } from '@angular/core';
@Component()
export MyComponent implements OnInit {
yourData;
public constructor(myService: MyService) {}
ngOnInit(){
myService.loadData()
.subscribe(s=> yourData = s);
}
}
OnInit 是一个生命周期钩子,在 Angular 初始化指令的所有数据绑定属性后调用。
推荐阅读
- typescript - 从没有初始化的对象生成函数或从类型中获取键并通过键创建函数
- node.js - 将图像上传到 AWS S3 被拒绝访问
- python - 将日志从 python 推送到 Splunk
- php - SQL 选择 col1 等于逗号分隔字符串中的值之一的所有行
- html - 验证 Laravel 中的只读字段
- python - 您知道以这种方式在列表列表中转换列表的快速方法吗?
- next.js - 如何获取我的 Next.JS API 电子邮件路由以将主机 IP 地址发送到 SendGrid?
- linux - 如何在x86 linux nasm程序集中将两个不同长度的数字相加
- python - 通过字典列表的键重新编码值
- c# - 使用 WebApplicationFactory 运行集成测试时出现“未配置应用程序”错误