0

I have one class with one fuction in it, and another class that will import the first class and use that function. After the function operates i need one value, but i am not getting any value afte the function.

First class:

export class MoveEff {

    checkEffect(effectFaceOff1,moveEff1,moveEff2){
        if ( effectFaceOff1=== 'grassgrass') {

            moveEff1 = 10;
            console.log(moveEff1);

        }
    }
}

Second class :


import { Component, OnInit } from '@angular/core';
import {GenIService} from "../Pokemons/gen-i.service";
import {MovesService} from "../Moves/moves.service";
import {MoveDataClass} from "../MoveDATA/move-data-class";
import {MoveEff} from "../MoveDATA/move-eff";

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage implements OnInit {

  effectFaceOff1;
  moveEff1;
  moveEff2;

constructor(private moveeff: MoveEff) {}

 this.moveeff.checkEffect(this.effectFaceOff1,this.moveEff1,this.moveEff2);

 console.log(this.moveEff1,this.moveEff2);

On the last console.log i should be seeing the 10 value of moveEff1, but it appears undefined.

Why? and how can i solve it?

Fábio Heitor
  • 105
  • 2
  • 12
  • The code is _not_ assigning a member field (it is a assigning to a global variable). Thus, “this.moveErf1” is not expected to be changed when accessed later. Other things might be wrong as well.. – user2864740 May 28 '20 at 23:38
  • are you asking about console in MoveEff? – rohith May 28 '20 at 23:41
  • How do assign it then? – Fábio Heitor May 28 '20 at 23:48
  • should i create variables in the MoveEff class? – Fábio Heitor May 28 '20 at 23:48
  • JS doesn't pass references to primitive values; you cannot change variables passed like that. If you pass objects however, you can change them: https://jsfiddle.net/khrismuc/2xe3nc9m/ –  May 29 '20 at 08:28
  • Does this answer your question? [Pass Variables by Reference in Javascript](https://stackoverflow.com/questions/7744611/pass-variables-by-reference-in-javascript) –  May 29 '20 at 08:29

2 Answers2

0

Exporting the class may not be enough. Try exporting and importing all your methods as modules, or exporting the method directly.

Unrefined
  • 77
  • 4
0

i don't know where you are getting effectFaceOff1, moveEff1 and moveEff2 from, but if they are @Input, their values cannot be retrieved in the constructor.

In that case, you should move your code to the ngOnInit:

ngOnInit() {
  this.moveeff.checkEffect(this.effectFaceOff1,this.moveEff1,this.moveEff2);
  console.log(this.moveEff1,this.moveEff2);
}

Last but not least, MoveEff should be made an Injectable in order to provide it to your class:

@Injectable({ providedIn: 'root' })
export class MoveEff {
  checkEffect(effectFaceOff1,moveEff1,moveEff2){
    if ( effectFaceOff1 === 'grassgrass') {
        moveEff1 = 10;
        console.log(moveEff1);
    }
  }
}
S P
  • 4,615
  • 2
  • 18
  • 31