简体   繁体   中英

How do I wait for users to click on certain buttons in component, then return a value from that in a function depending on which button was pressed?

I have an overlay component that appears when a user clicks on certain things in my page, and in this overlay it gives a warning and 2 buttons, one for yes and the other for no. What I want is to create a function that'll serve this component, and then it will wait for the user to respond, and subsequently return true or false based on what button was pressed. This boolean result can then be used to further progress to other code.

This is what I have tried already. It uses promises rather than rxjs observables. A component will call this function to bring the overlay from the service, eg this.service.promptUser().then(res => if (res === true) { doSomething() }) .

In the service:

didContinue: boolean = null;

async promptUser() {
    this.showOverlay.next(true) //BehaviourSubject when true brings the popup
    await waitForUser();
    const decision = this.didContinue;
    this.closeOverlay(); //sets didContinue back to null
   
    return decision
    }

The didContinue is a property inside of the service to indicate whether they have clicked yes or no using a boolean. Otherwise it will remain null. The click events from the overlay component will set the property didContinue to true or false.

The waitForUser function to wait for the user's input:

async waitForUser() {
    while (this.didContinue === null) {setTimeout(() => {}, 50};
    }

Currently it'll get stuck at the waitForUser() function but the popup will have not rendered at that stage, so the user can't input anything, the didContinue property will never change, and the application will freeze.

Please do send it forward if you know of an existing solution, I miss a lot of things with my google-foo. I am currently still new to Angular.

  1. Create a service that will handle the result

  2. inject service in your component where you want to use it like this

  3. constructor(public popService: popService) { } // create functions accordingly in service

  4. Call service method with the help of constructor on click() event like this

    <button (click)="popService.success()">Done

    <button (click)="popService.cancel()">Done i hope this will help, let me know if you need further help:-)

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