My objective sounds straightforward, but I am struggling to implement it: I want one of my components to automatically update when a variable in a service changes.
To illustrate my issue, consider the following example:
Imagine having a service that increases or decreases a points counter. The counter value is modified by calling specific functions within the service. Additionally, the service determines whether the counter value is even or odd.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TestService {
Number: number = 0;
IsOdd: boolean = false;
constructor() {}
IncreaseNumber() {
this.Number = this.Number + 1;
this.IsOdd = !this.IsOdd;
}
DecreaseNumber() {
this.Number = this.Number - 1;
this.IsOdd = !this.IsOdd;
}
}
*Now, let's consider the component which requires knowledge about whether the figure is even or odd.
Initially, everything works fine! It correctly determines the parity!
But how can I ensure that every time the number in my service (test.service.ts) changes, the even/odd value also updates in my component (test.component.ts)?*
import { Component, OnInit } from '@angular/core';
import { TestService } from '../test.service'
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
IsOdd: boolean = false;
constructor(MyService: TestService) {}
ngOnInit() {
this.IsOdd = MyService.IsOdd;
}
}
What approach should I take?
Should my component subscribe
to the service somehow?
Or is there a function similar to ngOnInit
that I should use for updates?
Thank you in advance