I've recently started working with Angular, primarily using VueJS. I'm curious about how to detect when a variable is updated. In my case, the variable is being updated through a DataService. I came across ngOnChanges()
, but it seems that it only works for inputs.
Here's an overview of my code:
import { DataService } from "../../service/my.service";
export class MainPage {
myVar: String = ""; // this is the variable I want to monitor for changes
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 update 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 assistance would be highly appreciated! :)