Ala
Ala

Reputation: 1503

Can not use a model in a component template

I have the following class:

export class Constants {

public static cREQUESTED_SERVICE: string = "RequestedService";
}

and I have the following template (Service.component.html) of component (Service.component.ts):

<label>{{Constants.cREQUESTED_SERVICE}}</label>

I have already imported (Constants) class inside (Service.component.html). The problem is: The label is displayed empty and the following error is logged in the console:

Subscriber.js:240 Uncaught TypeError: Cannot read property 'cREQUESTED_SERVICE' of undefined

Upvotes: 1

Views: 39

Answers (2)

Aravind
Aravind

Reputation: 41571

When ever you are using constants you should be using them as injectable() as they remain same through out the life cycle of the application(singleton) just like any other provider

@Injectable()
export class Constants {

public readonly cREQUESTED_SERVICE: string = "RequestedService";
}

In your component you should inject into constructor and use

constructor(private cons : Constants){}

this.cons.cREQUESTED_SERVICE

Upvotes: 3

Tiep Phan
Tiep Phan

Reputation: 12596

in your Service.component.ts, create another getter method like this

import { Constants } from 'your/path/to/this/file/Constants';

export class ServiceComponent {
  get ConstantsClass() {
    return Constants;
  }
}

in template

<label>{{ConstantsClass.cREQUESTED_SERVICE}}</label>

Upvotes: 3

Related Questions