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:
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 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>
I hope i understand what you are trying to achieve, if what you want is to move the entire up() function to the breakDown function you can copy the entire function to elevator.service.ts and call in the component constructor "public" instead of "private".
constructor(public elevatorService: ElevatorService) {}
then you can call it from the HTML
<input type="button" value="Up" (click)="elevatorService.breakDown()" [disabled]="buttonsDisabled" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.