user3387471
user3387471

Reputation: 113

angular code optimization about $http request

my code :

    app.factory('requestData',function($http,$q){
       return {
        reqData:function(params,url){
            return $http.get(url,{"params":params}).then(function(data){
                return data.data
            });
        });

    requestData.reqData( {module:"channel"},'/channel' ).then(function(data){
            $scope.selectChannel = data.value;
        })
     .then(function(){

         requestData.reqData( {channel_id:$scope.selectChannel},'/channel').then(function(data){
             $scope.summary = data.summary;
         })

      })
     .then(function(){
        //use $scope.summary do something
      });

firstly,i must set "$scope.selectChannel" value by asynchronous,then i use "$scope.selectChannel" to request. there is another method to achieve?

Upvotes: 0

Views: 253

Answers (2)

soytian
soytian

Reputation: 318

I advice you to use $resource instead.

.factory("$$service", ["$resource", function ($resource) {
    return $resource('/channel',
        {
            module: "@module",
            channel_id: "@channel_id"
        };
}]);

and use in this way:

var service = new $$service();
service.$get({"module":"channel"})
    .then(function(data){
        return service.$get({"channel_id":data.value});
    })
    .then(function(data){
        $scope.summary = data;
    });

Upvotes: 1

Jazzy
Jazzy

Reputation: 6129

Try something like this:

app.factory('RequestData',function($http,$q) {
    var RequestData = {
        // assuming params is an object
        reqData: function(params) {
            $http.post('/channel', params).then(function(response){
                RequestData.selectChannel = response.value;
            });
        }
    };

    return RequestData;
});

In your controller, inject RequestData as a dependency then set $scope.RequestData = RequestData then you will have access to RequestData.selectChannel in your views.

Upvotes: 1

Related Questions