Sydney Loteria Sydney Loteria - 1 month ago 9
AngularJS Question

Declare a Class in root component and use in other component

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?

Answer

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';