search

Home  >  Q&A  >  body text

angular.js - The result of AngularJS asynchronous request data is delivered, deferred.promise is unstable

AngularJS After asynchronously requesting data, use deferred.promise to pass the value, but it is very unstable. It is refreshed 10 times and only displayed 2 times.
I don’t know what’s wrong with my code, or if there’s a better way, please enlighten me!

Service file: service.js
<pre>
app.factory('Factory',['$sce','$q','$http',function($sce,$q ,$http){

var _baseUrl="//api.a.com",deferred = $q.defer(),service={};
service.list=function(_params){
    query({item:"/a/index",params:_params}).success(function(data){
        if(data.code==0){
            deferred.resolve(data.data);
        }else{
            alert("Error");
        }
    });
    return deferred.promise;
}
var query=function(rq){
    var item=rq['item'],params=rq['params'];
    return $http({
        method:"POST",
        url:_baseUrl+item,
        params:params,
        headers:{'Content-Type': 'application/x-www-form-urlencoded'}
    }).error(function(data){
        $.notify({message:_ay.system.code.api.error[data.code]},{type:"danger"});
    });
};
return service;

}
</pre>
Controller file: controller.js
<pre>
app.controller('ctrl.detail',['$scope','$ routeParams','Factory',function($scope,$routeParams,Factory){

var _param=$routeParams,_id=_param.g,_token=token;
$scope.d_detail={};
$scope.detail=function(){
    Factory.list({token:_token,device_id:_id}).then(function(data){
        $scope.d_detail=data.row;
    });
};
(init = function(){
    $scope.detail();
})();

}]);
</pre>
Page display
<pre>
<p data-ng-controller="ctrl.detail">

<li data-ng-bind="d_detail.id"></li>
<li data-ng-bind="d_detail.name"></li>

</p>
</pre>

为情所困为情所困2793 days ago653

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-05-15 16:56:40

    service.list = function (_params) {
        var deferred = $q.defer();
        query({ item: "/a/index", params: _params }).success(function (data) {
            if (data.code == 0) {
                deferred.resolve(data.data);
            } else {
                alert("Error");
            }
        });
        return deferred.promise;
    }

    reply
    0
  • 黄舟

    黄舟2017-05-15 16:56:40

    Factory.device_detail I didn’t see your definition

    reply
    0
  • Cancelreply