0

I am trying to show in a table a flag icon if the person who made a booking has had an order canceled in the past.

When admin changes a booking status to cancelled it sets a 'hasCanceled' boolean to true on the user who made the booking in firebase.

in my HTML table I am using an *ngIF to run a function and show the icon if the function returns true passing the order key as a parameter to the function.

<td><i *ngIf="hasUserCanceled(order.$key)" class="fa fa-flag"></i></td>

and here is the function itself:

hasUserCanceled(key) {

    //Get the userId from the order
    this.order = this.af.object('/orders/' + key);
    this.order.subscribe(res => {
      this.userId = res.userId;
    });

    this.canceledUsers = this.af.object('/users/' + this.userId);
    this.canceledUsers.subscribe((res) => {
      this.hasCanceled = res.hasCanceled
    });

    if (this.hasCanceled == true) {
      console.log('THIS IS TRUE')
      return true
    }

  }

I can see the flag in the right places of the users who have canceled, so the functions purpose is working, But the issue is that in the console, the function is running over and over and not stopping. Is there anything noticeable that I am doing wrong?

Console log Image: console log

KENdi
  • 7,576
  • 2
  • 16
  • 31
Brian Revie
  • 548
  • 1
  • 8
  • 24
  • The function will run each time change detection happens and the function itself will trigger change detection. Also: https://stackoverflow.com/q/14220321/6680611 – cartant Aug 13 '17 at 18:56
  • Thanks for your comment, I don't really understand what you mean, I took a look at the link you shared, but the page is so long I did not know where to look, I tried to find something that would help me but I am lost. – Brian Revie Aug 13 '17 at 19:06
  • Is there a way of doing this without calling a function in the HTML? perhaps in the constructor? I used a function so I can pass the order.$key back to the function to target each order in the table, so that I could flag the particular order which has previously been canceled. – Brian Revie Aug 13 '17 at 21:49
  • I think you will struggle to get an answer to this, as the code has several major problems. One is that you pass `order.$key` to `hasUserCanceled` which then reassigns to `this.order` - which means the change detection will want to call `hasUserCanceled` again, and the process repeats. Another problem is that `hasUserCanceled` is called as if it can obtain a synchronous result. It cannot, as the Firebase calls - initiated via the `subscribe` calls - are asynchronous. That's what the linked question relates to. – cartant Aug 14 '17 at 01:54
  • You are correct @cartant I had to restructure the whole code to make it work. Thank you for taking the time to help point this out to me and explain why. Really appreciate your help! – Brian Revie Aug 14 '17 at 06:33

0 Answers0