Angular2 全球服务商 [英] Angular2 global service provider
问题描述
/app
- app.component.ts
- app.component.html (hide/show: menu bar)
- app.global.service.ts (Public varible LoginSuccess:boolean)
- main.ts
/student
- student.ts
- student.service.ts
- student.component.ts
- student.component.html
/security
- login.component.ts (LoginSuccess = true)
- login.component.html
在我的 Angular2 应用程序中,我有一个简单的需求,我想根据登录成功显示隐藏菜单栏.为此,我创建了一个只有 LoginSuccess 布尔变量的服务,我将在登录组件上设置它,并将在 app.component.html 上用于 [hidden]=LoginSuccess
导航标签.
In my application of Angular2, I have a simple need where I want to show hide menu bar based on login success. For that I created a service which just have a LoginSuccess boolean varilable, which I would set on login component and will use on app.component.html for [hidden]=LoginSuccess
nav tag.
我面临的问题是,即使在通过 app.component.ts & 的
值不是持久化的,每个构造函数都会创建 constructor
注入 app.global.service.ts
之后login.component.tsapp.global.service.ts
的新对象.
Problem I am facing is, even after injecting app.global.service.ts
thru constructor
of app.component.ts & login.component.ts
value is not persisting and each constructor creating new object of app.global.service.ts
.
问题:我如何通过服务实现跨应用程序保持单个值.在 Angular2 文档的某个地方,我确实读到可注入服务是单例的.
Question: How can I achieve to persist single value across application thru service. Somewhere in Angular2 docs, I did read that Injectable service is singleton.
推荐答案
你应该在引导时提供 GlobalService
,而不是为每个组件提供:
You should provide GlobalService
at bootstrap, and not for each component:
bootstrap(AppComponent, [GlobalService])
@Component({
providers: [], // yes
// providers: [GlobalService], // NO.
})
class AppComponent {
constructor(private gs: GlobalService) {
// gs is instance of GlobalService created at bootstrap
}
}
这样 GlobalService
将是一个单例.
This way GlobalService
will be a singleton.
有关更高级的方法,请参阅此答案.
For more advanced approach see this answer.
这篇关于Angular2 全球服务商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!