Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular TypeError: Cannot read property 'then' of undefined

Tags:

angularjs

I have a data service like this:

this.myFunction= function(callback) {
    var url = rootURL + "path1/path2/service.json";
    var promise = $http.get(url);
    promise.then(function(payload){
        return callback(payload); 
    });
    return promise; 
}

It is called in a controller to initialize some stuff:

DataService.myFunction(function(data) { 
    if(data.statusText !== "OK"){
        $scope.$worked= false; 
    }else{  
        $scope.$worked= true;               
    }
}

And I get "TypeError: Cannot read property 'then' of undefined". Console.log(data) in the callback shows a 200 "OK" response and the data I expect. I have searched for this error already and mostly it is due to not returning the promise in the service. However, I'm returning the promise. Setting anything on the controller scope in the callback causes the error.

Angular version: AngularJS v1.3.0-rc.2

Thanks!

like image 800
DragonMoon Avatar asked Oct 04 '14 01:10

DragonMoon


1 Answers

You don't need to return a promise in this case, because you are using a callback. Callbacks and promises are the two ends of the spectrum. You can accomplish what you want simply with this.

If you want to use a callback you can leave your controller code.

this.myFunction= function(callback) {
    var url = rootURL + "path1/path2/service.json";
    $http.get(url).then(function(response) {
        callback(response.data);
    });
}

Or if you want to utilize the promises

this.myFunction= function() {
    var url = rootURL + "path1/path2/service.json";
    return $http.get(url).then(function(response) {
        return response.data;
    });
}

DataService.myFunction().then(function(data) { 
    if(data.statusText !== "OK"){
        $scope.$worked = false; 
    } else {  
        $scope.$worked = true;               
    }
});
like image 102
Zack Argyle Avatar answered Oct 01 '22 02:10

Zack Argyle