如何修复 Angular Service ngOnInit() 未被调用
问题:
你有一个实现 OnInit 的 Angular 服务:
my-service.ts
import { Injectable, OnInit } from '@angular/core';
@Injectable()
export class MyService implements OnInit {
constructor() { }
ngOnInit() {
console.log("MyService initializing");
}
}但它从不打印 MyService initializing - 即 ngOnInit() 函数从未被实际调用。
解决方案
服务不应实现 OnInit,该函数故意从不被调用。相反,将 ngOnInit() 中的代码添加到 constructor() 中,并删除 implements OnInit 和 ngOnInit():
my-service.ts
import { Injectable, OnInit } from '@angular/core';
@Injectable()
export class MyService {
constructor() {
console.log("MyService initializing");
}
}Check out similar posts by category:
Angular, Typescript
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow