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.ts通constructor的app.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将是一个单身人士.
有关更高级的方法,请参阅此答案.
你应该有一个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)
摘要:
app.component.tsapp.component.ts为provider参考:角度依赖注入
| 归档时间: |
|
| 查看次数: |
29994 次 |
| 最近记录: |