Angular2全球服务提供商

Avi*_*ale 15 angular2-services angular

/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
Run Code Online (Sandbox Code Playgroud)

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

我现在面临的问题是,即使注射后app.global.service.tsconstructorapp.component.ts & login.component.ts价值不是持久的,并且每个构造函数创建的新对象app.global.service.ts.

问题:如何通过服务在应用程序中保持单个值.在Angular2文档的某个地方,我确实读到了Injectable服务是单例.

Sas*_*sxa 29

您应该GlobalService在bootstrap中提供,而不是为每个组件提供:

bootstrap(AppComponent, [GlobalService])

@Component({
  providers: [], // yes
  // providers: [GlobalService], // NO.
})
class AppComponent {
  constructor(private gs: GlobalService) {
    // gs is instance of GlobalService created at bootstrap
  }
}
Run Code Online (Sandbox Code Playgroud)

这种方式GlobalService将是一个单身人士.

有关更高级的方法,请参阅此答案.

  • 但如果我不将它添加到提供者:[]我得到一个错误; 例外:没有GlobalService的提供商! (7认同)
  • 我如何在 angular 中使用它?因为我在 app.module 中有 angular 4 的语法是这样的。`bootstrap: [ AppComponent ]` 并且当我添加这样的服务时 `bootstrap: [ AppComponent, SharedService ]` 或 `bootstrap: [ AppComponent, [SharedService] ]` 我收到一个错误,我无法添加用于引导的服务像这样。任何人都可以对此有任何想法吗? (2认同)

the*_*het 7

你应该有一个app.component.ts而不是boostrapping app.module.ts你注入服务app.component.ts.

...
import { MusicService } from './Services/music-service';

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    providers: [MusicService],
    ...
})
export class AppComponent {

constructor(private MS: MusicService) {

}
...
Run Code Online (Sandbox Code Playgroud)

这是基于当前Angular2版本.所以里面index.html你应该有<app-root>哪里AppComponent被加载.

现在要在任何其他组件中使用它只需导入它:

import { MusicService } from './Services/music-service';
Run Code Online (Sandbox Code Playgroud)

并初始化它:

constructor(private MS: MusicService) {

}
Run Code Online (Sandbox Code Playgroud)

摘要:

  1. 导入到 app.component.ts
  2. 插入app.component.tsprovider
  3. 在构造函数中初始化
  4. 对于希望使用它的每个其他组件使用重复步骤2,3

参考:角度依赖注入