0

i've been trying to not use $scope when returning data from $http.get()

var app = angular.module('myApp',[])

app.controller('OrderCtrl',['$http',function($http){
    this.commande = null
    this.orders = {
        cde : null,
        start : '2014-01-01',
        end : '2014-01-31',
        get :  function(){
            return $http.get('http://apimucommerce/api/order/'+this.start+'/'+this.end+'/')
                .then(function(response){
                    return  response.data})
        }
    }

    this.commande = this.orders.get()
}])

the ajax call is returning datas, but i cannot assign to the this.commande property, what's wrong thanks.

1 Answer 1

2

this.orders.get() returns a promise (from $http), not data. This is because it's asynchronous, and needs to fetch the data before it can return. The proper pattern for getting the data is:

var app = angular.module('myApp',[])

app.controller('OrderCtrl',['$http',function($http){
    var self = this;
    this.commande = null
    this.orders = {
        cde : null,
        start : '2014-01-01',
        end : '2014-01-31',
        get :  function(){
            return $http.get('http://apimucommerce/api/order/'+this.start+'/'+this.end+'/')
                .then(function(response){
                    return  response.data})
        }
    }

    this.orders.get().then(function(data){
      self.commande = data;
    })
}])
Sign up to request clarification or add additional context in comments.

2 Comments

One problem here, this in the then callback no longer refers the controller
Good call, created an alias using a self variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.