DragonMoon
DragonMoon

Reputation: 411

Angular TypeError: Cannot read property 'then' of undefined

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!

Upvotes: 13

Views: 60640

Answers (1)

Zack Argyle
Zack Argyle

Reputation: 8407

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

Upvotes: 22

Related Questions