gpt4 book ai didi

javascript - 在服务初始化时执行一些代码

转载 作者:行者123 更新时间:2023-11-30 11:25:49 25 4
gpt4 key购买 nike

是否可以在服务初始化时执行一些代码。例如,当服务产品服务初始化时,我想执行这段代码:

this.var = this.sharedService.aVar;

最佳答案

Other than constructor there is NO lifecycle hooks for Service..

组件/指令支持生命周期钩子(Hook)

可注入(inject)对象是普通类(普通对象),因此它们没有特殊的生命周期。

@Injectable()
export class SampleService {
constructor() {
console.log('Sample service is created');
//Do whatever you need when initialized.
}
}

该类的构造函数被调用,所以这就是您的“OnInit”。至于销毁,服务并没有真正被销毁。

在一个服务需要另一个服务的地方使用dependency injection

@Injectable()
export class HeroService {


private yourVariable: any;
constructor(private sharedService: sharedService) {
this.yourVariable = this.sharedService.aVar;
}

关于javascript - 在服务初始化时执行一些代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48074253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com