Darius
Darius

Reputation: 69

Changing the value of variable from a service

I am creating an application in Angular and I want to change the value of variable through a service #function.ts

hide(menu) {
  console.log(menu)
  if (menu == true) {
    menu = false
  } else {
    menu = true
  }
}

main-component.ts

hide_menu() {
    hide(this.menu)
  }

In this case, I could see in the console that the menu is true but the value will not change.

Upvotes: 1

Views: 328

Answers (3)

Deepak Shah
Deepak Shah

Reputation: 1

hide(menu) {
 return !menu //more short
}

hide_menu() {
 this.menu = hide(this.menu);
 this.menu=!this.menu //more if service will not use then
}

Upvotes: 0

Kamil Augustyniak
Kamil Augustyniak

Reputation: 429

Boolean is a primitive type as string, number, undefined or null too. Primitive types are immutable. If you modify the method parameter which is a primitive type, it does not affect the original value (in main-component.ts). Reference types as an object, array or map are mutable so when you modify a copy (method parameter), the original would be modified too by reference.

In your case, you should return value and assign it in main-component.ts

hide(menu) {
 return !(menu == true) // shortened form but result is the same
}

hide_menu() {
 this.isHidden = hide(this.menu);
}

Upvotes: 1

KamilCz
KamilCz

Reputation: 93

Your service method should return a value.

hide(menu) {
  console.log(menu)
  if (menu == true) {
    menu = false
  } else {
    menu = true
  }
  return menu;
}

Then you need to assign value here:

hide_menu() {
  this.hide =  hide(this.menu);
}

If menu was an object you could pass it "by reference". But if its boolean value it won't change outside your function. It is described good here: Pass Variables by Reference in Javascript

Upvotes: 2

Related Questions