13
votes

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!

1
Can you post the callback function? Also there is not need to assign you get call to a variable it is already a promise and you could just call the .then on it. - Jared Reeves
Could you provide a plunkr or more context? It appears that that code should not throw that TypeError. - Jon7

1 Answers

22
votes

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;               
    }
});