Optiq
Optiq

Reputation: 3182

Function inside a class not triggering

I'm experimenting with different ways of implementing Typescript classes and I am having a hard time figuring out how to get my function to work properly.

So far this is what I have:

calc-func.ts :

export function calcFunc( a: number, b: number ){ return a*b; }

callc-class :

import { calcFunc } from './calc-func';

export class CalcClass implements calcFunc {
  NumA: number = null;
  NumB: number = null;
  NumC: number = calcFunc( this.NumA, this.NumB );
}

app.component :

export class App implements OnInit {

    Calculation: CalcClass = new CalcClass();

    ngOnInit(){
      this.Calculation.NumA = 3;
      this.Calculation.NumB = 7;
   }
}

app.component (template) :

 <h2>number = {{Calculation| json}}</h2>

NumC is showing up as 0 instead of 21 even though NumA is showing up as 3 and 'NumB' shows up as 7 as I'm aiming for.

What else do I need to do to make this work?

Upvotes: 1

Views: 56

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

The variable NumC is initialized when the CalcClass object is created, and it is not updated after that. If you want NumC to call calcFunc each time you access it, you should define it as a property:

get NumC(): number {
    return calcFunc(this.NumA, this.NumB);
}

Upvotes: 2

Related Questions