Angular2全球服务提供商 [英] Angular2 global service provider

查看:216
本文介绍了Angular2全球服务提供商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/应用
         - app.component.ts
         - app.component.html(隐藏/显示:菜单栏)
         - app.global.service.ts(公共varible LoginSuccess:布尔)
         - main.ts
        /学生
             - student.ts
             - student.service.ts
             - student.component.ts
             - student.component.html
        /安全
             - login.component.ts(LoginSuccess =真)
             - login.component.html

在我Angular2应用,我有一个简单的需求,我想基于登录成功,显示隐藏菜单栏。对于我创建了只是有一个LoginSuccess布尔varilable,我会在登录组件设置,并将于app.component.html使用服务[隐藏] = LoginSuccess 导航标签。

问题我面对的是,即使注射<$的 app.global.service.ts 直通构造之后C $ C> app.component.ts&安培; login.component.ts 值不是持久的,每个构造函数创建 app.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 将是一个单例。

有关更高级的方法请参见这个答案

For more advanced approach see this answer.

这篇关于Angular2全球服务提供商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆