Josh
Josh

Reputation: 464

Angular 2 not detecting changes in service variable from component

Good afternoon,

I'm trying to update my component to display the correct value of a service variable when it changes. I currently have this:

Component1 HTML

{{icons | json}}

Component1

icons: {
  icon1: boolean,
  icon2: boolean,
}

constructor(private _service: Service1) {
  this.icons = this._service.navIcons;
}

Component2

constructor(private _service: Service1) {
  this._service.signIn();
}

Service1

navIcons: {
  icon1: false,
  icon2: false
}

navIconsChange: Subject<any> = new Subject<any>();

constructor() { 
  this.navIconsChange.subscribe((value) => { this.navIcons = value; console.log(value) });
}

resetIcons() {
  this.navIconsChange.next(
    this.navIcons = {
       icon1: false,
       icon2: false
    });
}

signIn() {
  this.navIconsChange.next(
    this.navIcons = {
       icon1: true,
       icon2: true
    });
}

The idea is that when the signIn() method is called from Component2, the navIcons should update and those updates should display on Component1. The console.log I have in the subscribe logs that this change took place, however, the icons in Component1 HTML never update. I would assume these should automatically update since the icons are getting updated in Component1's constructor from Service1. How can I get these variables to update when Component2 calls the signIn() method?

This is all based off of this answer: https://stackoverflow.com/a/43161506/4927000

Thank you!

Upvotes: 0

Views: 3294

Answers (1)

Naman Kheterpal
Naman Kheterpal

Reputation: 1840

You need to modify much of your code as you are doing many things wrong way.

Component 1

icons: {
  icon1: boolean,
  icon2: boolean,
}

constructor(private _service: Service1) {
    this._service.navIconsChange.subscribe((value) => {
     this.navIcons = value; 
     console.log(value) 
    });
}

Service 1

navIcons: {
  icon1: false,
  icon2: false
}

navIconsChange: Subject<any> = new Subject<any>();

resetIcons() {
  this.navIconsChange.next({
       icon1: false,
       icon2: false
    });
}

signIn() {
  this.navIconsChange.next({
       icon1: true,
       icon2: true
    });
}

Component 2 and Component1 HTML will remain same.

This way your comopnent 1 will know when ever value gets changed.

Also if you want to cache the result in service for other component you can manually assign it to variable after .next or use BehaviourSubject like:

Service 1

navIcons = {
  icon1: false,
  icon2: false
}

navIconsChange: Subject<any> = new BehaviourSubject<any>(navIcons);

Add comments if you need further help.

Upvotes: 1

Related Questions