加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2全球服务提供商

发布时间:2020-12-17 09:28:56 所属栏目:安全 来源:网络整理
导读:/应用 – app.component.ts – app.component.html(隐藏/显示:菜单栏) – app.global.service.ts(公共变量LoginSuccess:boolean) – 主要 /学生 – student.ts – student.service.ts – student.component.ts – student.component.html /安全 – login.c
/应用
– app.component.ts
– app.component.html(隐藏/显示:菜单栏)
– app.global.service.ts(公共变量LoginSuccess:boolean)
– 主要
/学生
– student.ts
– student.service.ts
– student.component.ts
– student.component.html
/安全
– login.component.ts(LoginSuccess = true)
– login.component.html

在我的Angular2应用中,我有一个简单的需要,我想根据登录成功显示隐藏菜单栏.为此,我创建了一个只有一个LoginSuccess布尔varilable的服务,我将在登录组件上设置,并将在app.component.html上使用[hidden] = LoginSuccess nav标签.

我正在面临的问题是,即使在app.global.service.ts注入app.component.ts& login.component.ts值不存在,每个构造函数创建app.global.service.ts的新对象.

问题:如何通过服务实现跨应用程序的单一价值.在Angular2文档的某个地方,我看到可注入的服务是单身人士.

您应该在引导期间提供GlobalService,而不是为每个组件提供:
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 answer.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读