A
A
Alex102142021-12-06 19:07:33
Angular
Alex10214, 2021-12-06 19:07:33

Tracking changes in an Angular service?

Hello, I have such a dilemma.. There are 3 sliders:

<mat-slider (ngModelChange)="updateSliderValue($event)"
            [ngModel]="helpersService.slideValue1$.value"
            min="0"
            max="100"></mat-slider>
{{ helpersService.slideValue1$ | async }}

<mat-slider (ngModelChange)="updateSliderValue($event)"
            [ngModel]="helpersService.slideValue2$.value"
            min="0"
            max="100"></mat-slider>
{{ helpersService.slideValue2$ | async }}

<mat-slider (ngModelChange)="updateSliderValue($event)"
            [ngModel]="helpersService.slideValue3$.value"
            min="0"
            max="100"></mat-slider>
{{ helpersService.slideValue3$ | async }}
<button mat-raised-button color="primary">Primary</button>


export class MainComponent implements OnInit, AfterViewInit, OnChanges {

  constructor(
    private mainService: MainService,
    public helpersService: HelpersService
  ) {
  }

  ngOnInit(): void {
    console.log('slideValue1$', this.helpersService.slideValue1$.value);
    console.log('slideValue2$', this.helpersService.slideValue2$.value);
    console.log('slideValue3$', this.helpersService.slideValue3$.value);

  };


  ngAfterViewInit() {

  }

  ngOnChanges(changes: SimpleChanges) {
    
  }

  updateSliderValue(event: MatSliderChange){
    console.log(event);
    this.helpersService.slideValue1$.next(Number(event));
    this.helpersService.slideValue1$.pipe(take(1)).subscribe((e) => console.log(e));
  }
}


And there is a service with a BehaviorSubject:
import { Injectable } from '@angular/core';
import {BehaviorSubject} from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class HelpersService {
  slideValue1$: BehaviorSubject<number> = new BehaviorSubject(60);
  slideValue2$: BehaviorSubject<number> = new BehaviorSubject(50);
  slideValue3$: BehaviorSubject<number> = new BehaviorSubject(40);
  constructor() { }
  
}


Please tell me how to track the change in one slider and overwrite the desired subject?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2021-12-06
@Alex10214

The question is not clear. Subscribe to change data and change data in another.

<mat-slider (ngModelChange)="helpersService.slideValue1$.next(Number($event))"
            [ngModel]="helpersService.slideValue1$.value"
            min="0"
            max="100"></mat-slider>


ngOnInit(): void {
    this.helpersService.slideValue1$
        .pipe(
            takeUntil(this.destroy$),
            tap(value => {
                this.helpersService.slideValue2$.next(value);
            )
        )
        .subscribe();
};

// или с методом
updateSliderValue(event: MatSliderChange){
    this.helpersService.slideValue1$.next(Number(event));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question