The error I'm going to describe here seems to be very common; I've read many pages on the web (comprised some posts on this forum), but I haven't found any solution, maybe due to the fact that I'm new to AngularJS.
I designed a service which has a function whose sole role is retrieving a resource and returning it:
myApp.service('htmlGettersService', function ($http, $sce, $q) {
this.getHtmlIsa = function (codice_isa) {
return {
console.log("Get HTML Isa...");
var req = {
method: 'GET',
url: '/' + appName + '/api/quadri/' + codice_isa,
headers: {
'Content-Type': 'text/html;charset=UTF-8'
}
};
var htmlQuadri = {};
var deferred = $q.defer();
$http(req).then(function (response) {
htmlQuadri = $sce.trustAsHtml(response.data);
console.log("HTML Isa acquisito correttamente");
}, function (response) {
console.log("Errore in Get HTML Isa..." + response.message);
htmlQuadri = ("Errore in Get HTML Isa..." + response.message).promise;
});
deferred.resolve(htmlQuadri);
console.log("Exit from service function");
// return htmlQuadri;
return deferred.promise;
};
}
});
In this context, I had to insert a deferring tactic, since the service function seems to terminate before the GET call (and the success/failure function) have finished their work. Secondly, I tried to call service function from controller:
$scope.getHtmlIsa = function () {
htmlGettersService.getHtmlIsa($scope.codice_isa).then(function (response) {
$scope.htmlQuadri = response.data;
});
console.log("Controller: exit from getHtmlIsa");
}
At the end, I get the following error:
angular.js:14525 TypeError: Cannot read property 'then' of undefined
at ChildScope.$scope.getHtmlIsa (quadriController.js:51)
at Object.<anonymous> (quadriController.js:120)
at Object.invoke (angular.js:5003)
at $controllerInit (angular.js:10866)
at nodeLinkFn (angular.js:9746)
at compositeLinkFn (angular.js:9055)
at publicLinkFn (angular.js:8920)
at Object.link (angular-route.js:1223)
at angular.js:1346
at invokeLinkFn (angular.js:10426) "<ng-view class="ng-scope">"
I tried to use the same deferring tactic insiede controller, too; the error reported above disappeared, but it seems that controller function terminates before the service function has returned anything, so there's not enough time to save response from service inside controller variable. Any clue? Thanks for help.