Подтвердить что ты не робот

Angular 2 Метод инжектора поставщика глобальных констант

У меня есть глобальные константы, такие как корневой каталог, к которому я хочу, чтобы каждый компонент имел доступ. В другом вопросе stackoverflow ответ заключался в том, чтобы создать класс констант и импортировать его для каждого компонента.

Есть ли способ загрузить класс констант, чтобы каждый компонент приложения имел к нему доступ без какого-либо дополнительного импорта?

У меня это до сих пор, но он не работает, как я могу повысить класс констант, а затем получить доступ к моим компонентам?

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

Ответ 1

Чтобы ответить на ваши вопросы:

  • Все компоненты, использующие класс Constants, должны будут импортировать файл констант.

  • Чтобы использовать класс Constants, вам нужно вставить его в конструктор любых потребляющих компонентов, удалив функцию injector.get() из random.component.ts, например:

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

Вы также можете украсить свой постоянный класс как @Injectable и @Inject его в конструкторе вашего компонента.

Вот рабочий плункер.

Полезно загружать общие константы на уровне приложения, так что только один экземпляр класса создается и распределяется между всеми компонентами.

Ответ 2

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

Демо

Ответ 3

import {Component} from 'angular2/core'
import { Constants } from './constants'

@Component({
    selector: 'test',
    template: `  
                    Constants: <strong>{{ urlTemplate }}</strong>

              `
    providers:[Constants]

})

export class AppComponent{

  constructor(constants: Constants){
    this.urlTemplate = constants.root_dir;
  }

}

Вы можете использовать добавление Constants в providers:[Constants]


Декоратор @Injectable В этом случае не обязательно, но Google рекомендует всегда использовать. Вы можете увидеть здесь: https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#why-injectable- p >


/*
We recommend adding @Injectable() to every service class, even those that don't have dependencies and, therefore, do not technically require it. Here why:
Future proofing: No need to remember @Injectable when we add a dependency later.
Consistency: All services follow the same rules, and we don't have to wonder why a decorator is missing
*/

//@Injectable() 
export class Constants{
  root_dir: string;

  constructor(){
      this.root_dir = 'http://google.com/'
    }
  }

Plunker


В приложении @Inject вы можете прочитать что-то здесь: в чем разница между использованием (@Inject (Http) http: Http) или нет


Теперь, если вы хотите, чтобы это глобально можно было добавить в bootstrap

//main entry point
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app';
import { Constants } from './constants';


bootstrap(AppComponent, Constants)
  .catch(err => console.error(err));

//import { Injectable } from 'angular2/core'

//@Injectable()
export class Constants{
root_dir: string;

  constructor(){
      this.root_dir = 'http://google.com/'
    }
  }

import {Component, Inject} from 'angular2/core'
import { Constants } from './constants';

@Component({
    selector: 'test',
    template: `  
                    Constants: <strong>{{ urlTemplate }}</strong>

              `

})


export class AppComponent{

  constructor(@Inject (Constants) constants: Constants){
    this.urlTemplate = constants.root_dir;
  }

}

Plunker