Declare a Class in root component and use in other component

时间:2016-10-15 17:07:28

标签: angularjs angular

I have created this Global configuration class, this is the code:

import { Injectable } from '@angular/core';

@Injectable()
export class ConfigEnvironment {

    private development: String;
    private production: String;

    private ENV: String;

    private version: String;

    constructor(){
        this.development = "development";
        this.production = "production";

        this.ENV = this.development;

        this.version = "v1"
    }
    url(){

        var environment: any = this.ENV;

        var endPoint = {
            development: "http://localhost/meetup-api/"+this.version+"/",
            production: "https://localhost.production/meetup-api/"+this.version+"/"
        };

        return endPoint[environment];
    }
}

Declare the class in app.module.ts inside the providers like this:

providers: [ConfigEnvironment],

But when I access the ConfigEnvironment class in one of my component using this code:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  constructor(private router: Router) { }
  login () {
      console.log(ConfigEnvironment.url())
      this.router.navigate(['/']);
  }
  ngOnInit() {
  }

}

It gives me an error of "Cannot find name 'ConfigEnvironment'.

What seems to be the problem in my code?

2 个答案:

答案 0 :(得分:2)

You need to inject it to your component.

constructor(private router: Router, private configEnvironment : ConfigEnvironment ) { }

Also don't forget to import it.

import { ConfigEnvironment } from 'path/to/service';

答案 1 :(得分:1)

You have to import ConfigEnvironment in the class you are using it. If not you will get a typescript compilation error.