0

I am new to promise concepts and I'm facing a problem while I'm trying to submit a login form.

When the promise is resolved, I want to update the UI by changing the value of a scope variable.

Here is the controller method which is called

 $ctrl.loginForm = function(isValid) {
    // check to make sure the form is completely valid

    if (isValid) {
      LoginService.login($ctrl.user).then(function (value) {
          $ctrl.loginError = false;
          var cookie = value.token;
      }, function (reason) {
          $ctrl.loginError = true;

      });
    }

  };

and here is my service method

  service.login = function(credentials) {
    return new Promise((resolve, reject) => {
      $http.post(AppConst.Settings.apiUrl + 'api-token-auth/',credentials).success((data) => {
        resolve(data);
      }).error((err, status) => {
        reject(err, status);
      });
    });
  };

So once the promise is resolved the $ctrl.loginError in the controller changes its value but it does not update on the UI.

I've tried with $apply and it works, but I don't understand why I must use $apply! I thought that the digest cycle starts by default!

Am I doing something wrong?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Amazoom
  • 631
  • 1
  • 6
  • 9
  • no need to resolve promise like this in service. you can directly return your http call – ojus kulkarni Jun 04 '17 at 19:14
  • The $http service return a promise that trigger a digest after handled. Not need to wrap that on a native promise. You should accept @Denis Reshetniak answer. – Jaime Jun 07 '17 at 16:38

1 Answers1

0

$http methods return you a promise which is a $q service. So, problem is that you use native promise wrapper which doesn't tell angular's scope to run $apply method. Change your service to following

service.login = function(credentials) {
  return $http.post(AppConst.Settings.apiUrl + 'api-token-auth/',credentials);
};