简体   繁体   中英

Angular: trying to transfer the functions from the component to the service

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:

  1. 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

  1. 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

My stackblitz

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM