Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Change Detection - Angular

I'm fairly new to Angular, I work mainly with VueJS. I want to know how I can detect when a variable gets updated. I'm updating my variable through a DataService. I read about ngOnChanges() but I saw that this only works for inputs.

This is pretty much my code:

import { DataService } from "../../service/my.service";

export class MainPage {
  myVar: String = ""; // this is the variable I want to listen when a change is made

   constructor (
    private data: DataService
   ) {}

   ngOnInit() {
    this.data.changeVar.subscribe(message => this.myVar = message);
  }
}

my.service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject<string>("");
  changeVar = this.messageSource.asObservable();

  constructor() { }

  changeMyVar (message: string) {
    this.messageSource.next(message)
  }

}

This is where I'm updating the variable.

import { DataService } from "../../service/my.service";

export class AnotherPage {
  anotherVar: String = '';

  constructor(
    private data: DataService
  ) { }

  ngOnInit() {
    this.data.changeVar.subscribe(message => this.anotherVar = message)
  }

  myFunction () {
    this.data.changeMyVar("Hello"); // update variable to "Hello"
  }
}

Any help is greatly appreciated! :)

like image 265
Brian Moreno Avatar asked Apr 21 '18 22:04

Brian Moreno


2 Answers

If myVar is changed only in the Observable callback defined in ngOnInit, you can call a method after changing the variable:

export class MainPage {

    myVar: string = "";

    ngOnInit() {
        this.data.changeVar.subscribe(message => {
            if (message !== this.myVar) {
                this.myVar = message;
                this.doSomething();
            }
        });
    }

    private doSomething() {
        ...
    }
}

On the other hand, if myVar can be changed in other places (since it is public), you can access it in a getter/setter, and call the method in the setter:

export class MainPage {

    private _myVar: string = "";

    get myVar(): string {
        return this._myVar;
    }
    set myVar(value: string) {
        if (value !== this._myVar) {
            this._myVar = value;
            this.doSomething();
        }
    }

    ngOnInit() {
        this.data.changeVar.subscribe(message => this.myVar = message);
    }

    private doSomething() {
        ...
    }
}
like image 102
ConnorsFan Avatar answered Nov 10 '22 22:11

ConnorsFan


You can try use this: https://angular.io/api/core/OnChanges

and get the object changes with: changes.objectName

more details on the angular.io page.

like image 33
mariane muniz Avatar answered Nov 10 '22 23:11

mariane muniz