Angular button needs two clicks the first time the page is loaded

908 views angular
4

I want to create a validation function in Angular 6, where it checks if an object (a dish) already exists, based on the name. First I want to perform my getDishes method, to be able to search for a match.

Everything works fine when my two methods are combined in one, but I wanted to clean up some code (also for learning purposes).

With the code of the two distinct methods below, I need two clicks before the console.log logs the name.

So, can anybody tell my why:

  1. I need two clicks, what happends exactly why the method is not performed in time? I guess it has something to do with async?
  2. Is my workaround all right (using the code in OnInit)? In the end, the validation will always be necessary when adding a new dish.

    addDishWithDishExistValidation(): void {
    let dish = this.dishForm.value;
    
    for (let existingDish of this.getDishes()) {
      if (dish.name == existingDish.name) {
        console.log(existingDish.name);
      }
     }
    }
    
    getDishes(): Dish[] {
    this.dishService.getDishes()
      .subscribe(dishes => {
        this.dishes = dishes;
      });
    return this.dishes;
    }
    

However, When I put this part in OnInit, everything works fine:

    this.dishService.getDishes()
              .subscribe(dishes => {
                this.dishes = dishes;
              });

I did quite some research but could not find the answer for myself. Thanks in advance for the help!

answered question

1 Answer

9

Because on the first run:

  1. You do your 'validation' agains EMPTY Dish array
  2. You invoke async action to actually FETCH dishesh from service

On the second click action, async probably completes and then you validate agains some set of dishes. As your validation is async, you should use async validators to do that.

posted this

Have an answer?

JD

Please login first before posting an answer.