What you need is a service to maintain the state of your variables. You would then be able to inject that service into any component to set or get that variable.
Here's an example (/services/my.service.ts):
import {Injectable} from "angular2/core";
@Injectable()
export class MyService {
private myValue;
constructor() {}
setValue(val) {
this.myValue = val;
}
getValue() {
return this.myValue ;
}
}
You would probably want to put that service in the providers array of your app's bootstrap function (which might be in your main app component file, or in a separate file depending on how you like to do things).
In your main app file (/app.ts):
import {MyService} from './services/my.service';
bootstrap(App, [MyService, COMMON_DIRECTIVES, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, HTTP_PROVIDERS]); // directives added here are available to all children
You needn't have COMMON_DIRECTIVES and the other all caps items in the array, but those are commonly included just to make it so that you don't have to configure them in each component you write.
Then you would access the service from within a component like this (/components/some-component.ts):
import {MyService} from '../services/my.service';
@Component({
selector: 'some-component',
template: `
<div>MyValue: {{val}}</div>
`
})
export class SomeComponent {
constructor(private myService:MyService) {
}
get val() {
return this.myService.getValue();
}
}
You might also want to add to the service so that it saved the value to somewhere (semi) permanent so that it could be accessed the next time the user entered the application.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…