它可能在Angular 4/5 autoinstace服务提供商?

问题描述 投票:0回答:1

我有一些声明的服务

// 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

angular dependency-injection
1个回答
0
投票

为了实例化,应该注入提供者。大多数情况下,它通过将其注入根组件AppComponent来解决。

它也可以注入到模块构造函数或APP_INITIALIZER多提供程序中,但这取决于提供程序及其自身的依赖项的工作方式。其中一些选项可能会导致循环依赖或竞争条件。

© www.soinside.com 2019 - 2024. All rights reserved.