0

I'm working on implementing a favorite/unfavorite button right now using the Mean stack. I have the backend properly working and am trying to figure out how to conditionally show the correct button. There is a favorite and unfavorite button that use ng-show based on whether or not a particular post(thing to favorite) has already been favorited by the user. The issue is that Angular does not wait while the database is checking if this user has already favorited this post and thus should display the unfavorite button instead. I've messed around with $q and other async options, but I'm not very confident in my understanding of them. Here is the relevant code:

app.isFavorited = $q.defer();
if(Auth.isLoggedIn()) {
  app.isLoggedIn = true;
  Auth.getUser().then(function (data) {
    postObject.username = data.data.username;
    if(data.data.favorites.length == 0) {
      app.isFavorited.resolve(false);
      app.load = true;
    }
    for(var i = 0; i < data.data.favorites.length; i++) {
      if(id == data.data.favorites[i]) {
        app.isFavorited.resolve(true)
        app.load = true;
        break;
      }
      if(i == data.data.favorites.length - 1) {
        app.isFavorited.resolve(false);
        app.load = true;
      }
    }

  });
}
else {
  app.isLoggedIn = false;
  app.load = true;
}

line 55 executes before those which get the values used in ng-show:

line 55 executes before those which get the values used in ng-show

Pengyy
  • 37,383
  • 15
  • 83
  • 73
  • `.then` blocks are non-blocking. The JavaScript engine does not wait for the code inside `.then` blocks to complete. The code inside `.then` blocks executes when the data comes back from the server. That is why line 55 executes before lines 17 and 19. – georgeawg Apr 18 '17 at 07:08
  • @Claies but the for loop is inside of the .then block – Bijan Farahani Apr 19 '17 at 06:04
  • @georgeawg Do you have any recommendations for having the value wait for the server to deliver it? – Bijan Farahani Apr 19 '17 at 06:05
  • Generally one creates a promise for the value and puts any code that depends on that value inside a `.then` block that is chained from the promise. – georgeawg Apr 19 '17 at 07:03
  • Like @georgeawg says you should toggle some flags like isLoading and isFavorite. Initially $scope.isLoading = true, $scope.isFavorite = null. `promise.then(function(valueFromServer) { $scope.isFavorite = valueFromServer; }).finally(function() { $scope.isLoading = false; })`. Angular1 does not have a built-in concept of push notifications nor the directives support this concept. For example in Angular2 you can opt for using observables, which is the recommended way, and you can use them directly in your templates with the `async` pipe. – andreim Apr 19 '17 at 07:35
  • I fixed it by putting the assignment in the .then that comes from the async call its related to, not another (partially independent) one – Bijan Farahani Apr 24 '17 at 23:24

0 Answers0