Amble
Amble

Reputation: 227

Emitting Values into a service to populate another component

I'm reading the angular docs here (https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service). I'm trying to have a slider in one component, send its value to a service and then populate an item in another component. Basically the slider should update values in real time. I'm new to Angular, doing some pluralsight courses so I apologise if the framing is wrong here. At the moment, I'm having difficulty just getting the emitted value into the service, the servcie looks ...right but I can't get as far as testing.

I have the slider working and emitting the values into the console. Relevant part (wihtout defaults)

.TS

import { SliderService } from 'src/services/slider.service';
@Components {(   providers: [SliderService]  )}

export class AppComponent {  
  onInputChange(event: any) {
  console.log("This is emitted as the thumb slides");
  console.log(event.value);
  let slider = event.value;
 }

announce() {
let sliderVal = this.slider[this.nextMission++];
}

.HTML

<mat-slider thumbLabel (input)="onInputChange($event)"></mat-slider>

SERVICE

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SliderService {

private sliderTrackerSource = new Subject<number>();
sliderChanger$ = this.sliderTrackerSource.asObservable();
static sliderChanger$: any;

announceSlider(position: number)
{
  this.sliderTrackerSource.next(position);
}

constructor() { }
}

COMPONENT I WANT TO PASS THE DATA TO AND DISPLAY (TS), TRYING TO PUT DATA INTO sliderVal1

import { Component, OnInit } from '@angular/core';
import { SliderService } from 'src/services/slider.service';

@Component({
selector: 'app-stats',
templateUrl: './stats.component.html',
styleUrls: ['./stats.component.scss'],
providers: [SliderService]
})
export class StatsComponent implements OnInit {
public Sliderval1: any;

constructor() { }

ngOnInit(): void {
}

}

And one last question, when you have multiple sliders, how would you map them to different streams when calling the same service function?

Upvotes: 0

Views: 72

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

Your components are using different instances of the service.

Remove the SliderService from your component providers to allow both components to use the singleton instance of your service.

@Component({
  // ...
  providers: [SliderService] // remove this
})

Your service is already configured for injection as a singleton with this decorator:

@Injectable({
  providedIn: 'root'
})

Upvotes: 1

Related Questions