繁体   English   中英

then(函数)没有在angularjs中用返回的promise值更新

[英]then(function) not getting updated with returned promise value in angularjs

我试图借助angularjs中的promises从API获取一些数据。 我有一项服务是从API获取价值并将承诺返回给控制器。

***Service***
this.forgotPasswordLink = function(email){
    var deferred = $q.defer();
    $http.post('/forgotPassword',{
        email: email 
    }).success(function(response){
        console.log("the new response is: ",response);
        deferred.resolve(response);
    }).error(function(error){
        deferred.reject(error);
    });
    return deferred.promise;
};

**Controller**
authService.forgotPasswordLink($scope.forgotPasswordEmail).then(function(data){
        console.log(data);
        if(data.message === 'emailFound'){
            $scope.emailSent = true;
            $scope.emailNotSent = false;
        }
        else{
            $scope.emailNotSent = true;
            $scope.emailSent = false;
        }
    });

此处authservice是服务的名称。 所以这段代码可以正常工作,但是问题是当我一次又一次尝试多次获取数据时,第一次保证会返回正确的数据,但是当我尝试使用不同的数据进行发布时,保证不会更新(功能)即使Promise从服务器获得了正确的响应。

如果看到两个控制台语句,一个在服务中,一个在控制器中; 因此,当promise返回旧值时,首先执行控制器中的console语句,当promise解析时,将使用更新后的值执行正在使用的第二个console语句。

因此,如何在then(function)中获取更新的值。 发布数据一次后是否需要刷新服务?

正如@Terry所建议的那样,您完全不必依赖$ q来获得结果。 我推荐以下两种方法之一:

#1:

***Service***
this.forgotPasswordLink = function(email){
    return $http.post('/forgotPassword',{
        email: email 
    }).then(function(response){
        console.log("the new response is: ",response);
        return response;
    }).catch(function(error){
        return error;
    });
};

在这种情况下,控制器保持不变。 唯一需要注意的是,即使在错误情况下,也将调用控制器的then函数, data是从服务的catch块返回的错误对象。

#2:

***Service***
this.forgotPasswordLink = function(email){
    return $http.post('/forgotPassword',{
        email: email 
    });
};

***Controller***
authService.forgotPasswordLink().then(function(data){
    console.log(data);
    if(data.message === 'emailFound'){
        $scope.emailSent = true;
        $scope.emailNotSent = false;
    }
    else{
        $scope.emailNotSent = true;
        $scope.emailSent = false;
    }
}).catch(function(error){
    console.log(error); // Error handling like notifying user, etc...
});

在第二种方法中,服务仅返回$http返回的promise。 然后,控制器根据此承诺的结果采取措施。

有人可以说,获取数据并将其交给控制器采取行动是服务的职责。 这是第一种方法。

我个人更喜欢第一种方法,因为该服务很简单,并且以这种方式进行测试很容易。

当您使用then方法时,您已将.data放在变量之后,将data.data放在后面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM