我有一个全局常量,比如根目录,我希望每个组件都可以访问它。在另一个堆栈溢出问题中,答案是创建一个常量类并将其导入每个组件。
有没有一种方法可以引导常量类,使应用程序中的每个组件都可以访问它,而无需任何额外的导入?
到目前为止,我已经有了它,但它不工作,我如何引导常量类,然后在我的组件中访问它?
constants.ts
export class Constants{
root_dir: string;
constructor(){
this.root_dir = 'http://google.com/'
}
}main.ts
import {bootstrap} from 'angular2/platform/browser'
import {Constants} from './constants'
bootstrap([
provide(Constants, {useClass: Constants})
]);random.component.ts
import {Component, bind} from 'angular2/core';
import {Injector} from 'angular2/core';
@Component({
selector: 'my-app',
template: `{{test}}`
})
export class RandomComponent{
test: string;
constructor(){
this.test = injector.get(Constants.root_dir);
}
}发布于 2016-03-06 13:33:02
回答您的问题:
export class App {
constructor(constants: Constants) {
this.url = constants.root_dir;
}
}您还可以将常量类装饰为@Injectable,并将其@Inject到组件的构造函数中。
在应用程序级别引导共享常量是有益的,这样只会创建类的一个实例,并在所有组件之间共享。
发布于 2016-03-06 12:20:16
import {Component,bind,provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {FORM_DIRECTIVES} from 'angular2/form';
import {Directive, ElementRef, Renderer, Input,ViewChild,AfterViewInit} from 'angular2/core';
import {Constants} from 'src/constants'
import {ViewChild, Component, Injectable} from 'angular2/core';
@Component({
selector: 'my-app',
template: `{{test}}`,
})
export class App {
test: string;
constructor(cs:Constants){
this.test = cs.root_dir;
}
}
bootstrap(App, [Constants]);https://stackoverflow.com/questions/35822486
复制相似问题