I want to transfer the up function to the service and call them in the component.
A very simple app that is divided into several parts:
- In the service I have 2 functions:
getRandomNumbers - That every second shows a random number between 1 and 20
breakDown - If I press the up button 20 times it makes me disable the button
- In the component I have function of up:
- **up - The role of up function at the push of a button increases the number by +1
In stackblitz I will display the function (up) in the component And the code I'll send under it is what I tried to do to make it work
What I was trying to do:
My service:
export class ElevatorService {
floor = new BehaviorSubject<number>(1);
floorNumber: number = -1;
Count = 0;
getRandomNumbers() {
return interval(1000).pipe(
map(() => Math.floor(Math.random() * 20) + 1),
tap((res) => (this.floorNumber = res))
);
}
breakDown() {
this.Count++;
if (this.Count >= 20) return true;
return false;
}
up() {
this.breakDown();
this.floor
.pipe(
take(1),
filter((v) => v < 20),
map((v) => v + 1)
)
.subscribe((v) => this.floor.next(v));
}
My component.ts:
export class AppComponent {
floor = new BehaviorSubject<number>(1);
Count = 0;
buttonsDisabled: boolean = false;
ngOnInit(): void {
this.Count++;
this.elevatorService.getRandomNumbers().subscribe(this.floor);
}
constructor(private elevatorService: ElevatorService) {}
up() {
const up = this.elevatorService.up();
return up;
}
}
My component.html:
<input type="button" value="Up" (click)="up()" [disabled]="buttonsDisabled" />
<div class="elevator">
<pre class="floor">{{ this.floor | async }}</pre>
</div>