我有一些声明的服务
// app.module
@NgModule({
providers: [
AuthorsService
],
bootstrap: [
AppComponent
]
})
// authors.service
@Injectable()
export class AuthorsService {
public constructor() {
console.log('service constructor');
}
}
我可以为服务运行console.log
做一些事情,当像以前的代码一样添加到provices数组?
当服务开始时我需要做一些事情......我喜欢避免服务实例这样的代码:
public constructor(
protected authorsService: AuthorsService
) {
}
// only with that console.log is runned
(请不要问为什么,这是一个简单的例子for a better use on a library)
为了实例化,应该注入提供者。大多数情况下,它通过将其注入根组件AppComponent
来解决。
它也可以注入到模块构造函数或APP_INITIALIZER
多提供程序中,但这取决于提供程序及其自身的依赖项的工作方式。其中一些选项可能会导致循环依赖或竞争条件。