我在这里描述的错误似乎很常见;我已经在网上阅读了很多页面(包括本论坛的一些帖子),但是我还没有找到任何解决方案,可能是因为我是AngularJS的新手。AngularJS:从控制器调用服务函数时出错
因此我设计了具有其唯一的作用是获取资源,并恢复它的功能的服务:
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;
};
}
});
在这种情况下,我不得不插入延迟策略,因为服务功能似乎之前终止GET调用(以及成功/失败函数)已完成其工作。 其次,我试图从控制器调用服务功能:
$scope.getHtmlIsa = function() {
htmlGettersService.getHtmlIsa($scope.codice_isa).then(function (response) {
$scope.htmlQuadri = response.data;
});
console.log("Controller: exit from getHtmlIsa");
}
最后,我得到以下错误:
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">"
我试图用同样的战术推迟控制器insiede也;上面报告的错误消失了,但似乎控制器函数在服务函数返回任何内容之前终止,所以没有足够的时间来保存控制器变量中服务的响应。 任何线索? 感谢您的帮助。
你的代码是不可读的,对不起 – smnbbrv