Home > Net >  Angular: Trying to synchronize between 2 functions that I have in service
Angular: Trying to synchronize between 2 functions that I have in service

Time:06-06

I have 2 functions that work individually But I want to synchronize between them working together.

One function getRandomNumbers - Whose role is displayed every second at a random number between 1 and 20

Second function up - Button that allows me to change the number of getRandomNumbers At the push of a button the number will advance by 1

stackblitz

My code:

Service:

export class ElevatorService {

  floor = new BehaviorSubject<number>(3);
  floorNumber: number = -1;

  constructor() {
    this.floor.next(1);
  }

  getRandomNumbers() {
    return interval(1000).pipe(
      map(() => Math.floor(Math.random() * 20)   1),
      tap((res) => (this.floorNumber = res))
    );
  }


  up() {
    const floor = this.floor;
    floor.pipe(
        take(1),
        filter((v) => v < 20),
        map((v) => v   1),
        tap((res) => (this.floorNumber = res))

      )
      .subscribe((v) => this.floor.next(v));
      return floor;
  }

My component.ts:

export class AppComponent  {

  floor = new BehaviorSubject<number>(3);
  Count = 0;
  buttonsDisabled: boolean = false;

  ngOnInit(): void {
    this.Count  ;
    this.elevatorService.getRandomNumbers().subscribe(this.floor);
  }
  elevatorServiceFloorValue$ = this.elevatorService.floor;

  constructor(private elevatorService: ElevatorService) { }

  up() {
    this.elevatorService.up();
  }

My component.html:

<input type="button" value="Up" (click)="up()" />

<div >
  <pre >{{ this.floor | async }}</pre>
</div>

CodePudding user response:

You want to keep the state in the service and push that state to a subject:

floorSubject = new BehaviorSubject<number>(0);
floorNumber: number = 0;

get floor() {
   return this.floorSubject.asObservable()
}

You also had a reference to a count in your component, similar to some other users question I just had a look at. I removed it because it wasn't used in any meaningful way.

I made it so you just have to subscribe to getNumbers for it to start pushing random values to that same subject.

Here's the whole fix for your code on Stackblitz

  • Related