始终在 Angular 中包含一项服务
Always include a service in Angular
我有一个 cookie-service
负责显示 cookie 横幅以接受站点 cookie。如果用户接受它们,它也用于设置和获取 cookie。
我的问题是,如果我不在任何组件中包含该服务,cookie 横幅也不会显示。我也尝试了不同的方法在模块中提供它,但也没有用。有没有办法在 angular 中包含服务,即使它没有明确包含在任何组件中。
Update
I tried to register the service as suggested, however the console log
still won't show.
共享模块
@NgModule({
declarations: [
// ...
],
exports: [
// ...
],
imports: [
// ...
providers: [
CookieService,
// ...
],
})
export class SharedModule {
}
服务
更改了可注射部分
@Injectable({
providedIn: 'root'
})
@Injectable()
export class CookieService {
constructor() {
console.log('cookie service is alive');
}
// ...
}
编辑
作为解决方法,创建一个指令并在应用程序的根组件上使用它。在那里注入你的服务,你就完成了。您还可以将服务中的逻辑移至该指令中。这样你就不会用无用的注入污染你的组件。
或者,正如另一位用户所建议的,只需将它注入根组件并完成它(但一定要留下评论,说明为什么你只是在那里注入一些东西然后不使用它)
原创
我猜你的服务正在被 Webpack 摇树。为防止这种情况,请从 @Injectable
装饰器中删除 providedIn
,并将您的服务 class 放入 @NgModule
.
的 providers
数组中
以下是文档中的相关部分:
Registering the provider in the @Injectable() metadata also allows Angular to optimize an app by removing the service from the compiled application if it isn't used, a process known as tree-shaking.
Using the @Injectable() providedIn property is preferable to the @NgModule() providers array because with @Injectable() providedIn, optimization tools can perform tree-shaking, which removes services that your application isn't using and results in smaller bundle sizes.
只需将其注入您的 AppComponent
。这应该是这样的:
export class AppComponent {
constructor(cookieService: CookieService) { }
// ...
}
我有一个 cookie-service
负责显示 cookie 横幅以接受站点 cookie。如果用户接受它们,它也用于设置和获取 cookie。
我的问题是,如果我不在任何组件中包含该服务,cookie 横幅也不会显示。我也尝试了不同的方法在模块中提供它,但也没有用。有没有办法在 angular 中包含服务,即使它没有明确包含在任何组件中。
Update
I tried to register the service as suggested, however the console log still won't show.
共享模块
@NgModule({
declarations: [
// ...
],
exports: [
// ...
],
imports: [
// ...
providers: [
CookieService,
// ...
],
})
export class SharedModule {
}
服务
更改了可注射部分
@Injectable({
providedIn: 'root'
})
@Injectable()
export class CookieService {
constructor() {
console.log('cookie service is alive');
}
// ...
}
编辑
作为解决方法,创建一个指令并在应用程序的根组件上使用它。在那里注入你的服务,你就完成了。您还可以将服务中的逻辑移至该指令中。这样你就不会用无用的注入污染你的组件。
或者,正如另一位用户所建议的,只需将它注入根组件并完成它(但一定要留下评论,说明为什么你只是在那里注入一些东西然后不使用它)
原创
我猜你的服务正在被 Webpack 摇树。为防止这种情况,请从 @Injectable
装饰器中删除 providedIn
,并将您的服务 class 放入 @NgModule
.
providers
数组中
以下是文档中的相关部分:
Registering the provider in the @Injectable() metadata also allows Angular to optimize an app by removing the service from the compiled application if it isn't used, a process known as tree-shaking.
Using the @Injectable() providedIn property is preferable to the @NgModule() providers array because with @Injectable() providedIn, optimization tools can perform tree-shaking, which removes services that your application isn't using and results in smaller bundle sizes.
只需将其注入您的 AppComponent
。这应该是这样的:
export class AppComponent {
constructor(cookieService: CookieService) { }
// ...
}