To implement global variable, you could implement a shared service. You will be able to save data it and all components could have access to them.
For this, simply implement a service and set its provider when boostrapping your application:
bootstrap(AppComponent, [ MySharedService ]);
Be careful not to define it again within the providers
attribute of components where you want to use it.
Sample
The service:
export class MySharedService {
data: any;
dataChange: Observable<any>;
constructor() {
this.dataChange = new Observable((observer:Observer) {
this.dataChangeObserver = observer;
});
}
setData(data:any) {
this.data = data;
this.dataChangeObserver.next(this.data);
}
}
Use it into a component:
@Component({
(...)
})
export class MyComponent {
constructor(private service:MySharedService) {
}
setData() {
this.service.setData({ attr: 'some value' });
}
}
If you want to notify components that the data were updated you can leverage observable fields into the shared service:
@Component({
(...)
})
export class MyComponent {
constructor(private service:MySharedService) {
this.service.dataChange.subscribe((data) => {
this.data = data;
});
}
}
See this question for more details:
This page on the angular.io website could also interest you:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…