1

Context

I have an Angular 10 project that renders the following (I'm modelling an 8-bit computer):

enter image description here

This project makes use of an Angular service that looks like this (it will be encapsulating a more complex logic in the future, but I simplified the code to help focusing on the problem):

import { Injectable } from '@angular/core';
 
@Injectable({
   providedIn: 'root'
})
export class SapOneService {
 
   data = {
       bus: {
           bits: [1, 1, 1, 1, 0, 0, 0, 0]
       },
       registers: [
           {
               bits: [0, 0, 0, 0, 0, 0, 0, 1],
               load: false,
               enable: false
           },
           {
               bits: [1, 0, 0, 0, 0, 0, 0, 0],
               load: false,
               enable: false
           }
       ]
   };
 
   constructor() { }
 
   tick(): void {
       if (this.data.registers[0].load) {
           this.data.registers[0].bits = this.data.bus.bits;
       }
 
       if (this.data.registers[1].load) {
           this.data.registers[1].bits = this.data.bus.bits;
       }
 
       if (this.data.registers[0].enable) {
           this.data.bus.bits = this.data.registers[0].bits;
       }
 
       if (this.data.registers[1].enable) {
           this.data.bus.bits = this.data.registers[1].bits;
       }
 
       console.log(this.data);
   }
}

I have 4 Angular components that make use of this service:

  • (BLOCK: Register A and B) 2 components can read and edit the data contained on this.data.registers[0] and this.data.registers[1] respectively.
  • (BLOCK: Bus) 1 component can read and edit the data contained on this.data.bus
  • (BLOCK: Clock) The last component only has a button that when clicked calls the function tick() making all the data contained on this.data.registers[0], this.data.registers[1] and this.data.bus to change based on the rules inside that function.

I’m printing the data in the console and basically the logic works, but sadly the information on the components is not updated (the gray and red dots).

What I would like to achieve is: when the tick() method is called all the components update too.

Can someone help me on this please?

Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34
Bufofa
  • 13
  • 3
  • I found the solution on this post: https://stackoverflow.com/questions/34714462/updating-variable-changes-in-components-from-a-service-with-angular2 – Bufofa Sep 29 '20 at 19:13

1 Answers1

0

You can try adding a 'Subject' in your service as Observable. All of the components should subscribe to your observable (Subject). Whenever your subject emits a new value using 'next' all components subscribed to your subject will get notified. You can try looking at the documentation of 'rxjs subject': https://rxjs-dev.firebaseapp.com/guide/subject

paulhenry
  • 111
  • 5