Angular 2全局常数提供者注入器方法 [英] Angular 2 Global Constants Provider Injector Method

查看:88
本文介绍了Angular 2全局常数提供者注入器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像根目录这样的全局常量,我希望每个组件都可以访问.在另一个stackoverflow问题中,答案是创建一个常量类并将其导入每个组件.

I have a global constants like root directory that I want every component to have access to. In another stackoverflow question the answer was to create a constants class and import that to every component.

是否有一种方法可以引导常量类,以便应用程序中的每个组件都可以访问它而无需任何其他导入?

Is there a way to bootstrap a constants class so that every component in the app has access to it without any additional importing?

到目前为止,我已经有了它,但是它不起作用,如何增强常量类,然后在我的组件中进行访问?

I have this so far but it is not working, how do I boostrap the constants class and then access then in my components?

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);
    }
}

推荐答案

要回答您的问题:

  • 所有使用Constants类的组件都需要导入常量文件.

  • All components using the Constants class will need to import your constants file.

要使用Constants类,您需要将其注入到任何消耗组件的构造函数中,请从random.component.ts中删除jector.get()函数,如下所示:

In order to use the Constants class you need to inject it into the constructor of any consuming components, removing the injector.get() function from random.component.ts like so:

export class App {
  constructor(constants: Constants) {
    this.url = constants.root_dir;
  }
}

您还可以将常量类装饰为@Injectable,并@Inject将其装饰到组件的构造函数中.

You may also decorate your constant class as an @Injectable and @Inject it into the constructor of your component.

这是一个正在工作的矮人.

在应用程序级别引导共享常量是有益的,这样仅创建该类的一个实例并在所有组件之间共享.

It is beneficial to bootstrap the shared constants at the app level so that only one instance of the class is created and shared among all components.

这篇关于Angular 2全局常数提供者注入器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆