现在,当我的控制器开始包含更多代码和http请求时,我正在新建我的代码,如下所示:
someApp.controller("SomeCtrl", ["$scope", "$http", function ($scope, $http) {
// *** Variables ****
var someVar;
// **** HTTP ****
var httpSomeRequest = function () {
$scope.busyWithHttpRequest = true;
$scope.hideRequestError = true;
$http.get(someUrl).
success(function (data, status, headers, config) {
$scope.busyWithHttpRequest = false;
// Do success things
}).
error(function (data, status, headers, config) {
$scope.busyWithHttpRequest = false;
$scope.hideRequestError = false;
// Do error things
});
};
// **** Functions ****
var someFunctionNotUsedInHtml = function () {
// Do something here
};
// **** Scoped Functions ****
$scope.someFuntionUsedInHtml = function () {
// Do something here
};
// **** Start ****
$scope.busyWithHttpRequest = false;
$scope.hideRequestError = true;
someFunctionNotUsedInHtml();
}]);
现在我对这段代码的不确定性是:
答案 0 :(得分:0)
关于2,有一些选择:
2.1使用拦截器,例如参见http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/displaying-a-loading-spinner.html
2.2而不是将busyWithHttpRequest设置为false成功&错误最好在最终内部执行此操作。
我最终得到了2.2因为对我来说不那么复杂,而且通过定义一个(Resharper)模板,如果我忘记了什么,我就不会犯错误。
我发现另一个有趣的帖子(http://www.peterbe.com/plog/promises-with- $ http)关于http请求的1-for-all解决方案。我也在使用Angular的Bootstrap Typeahead。这符合承诺,因此上述结构不会对此有所帮助。最好使用以下结构,可以应用于所有http请求:
$scope.httpGetListForTypeAhead = function (id) {
$scope.busyWithHttpRequest = true;
$scope.showRequestError = false;
var encodedId = encodeURIComponent(id); // As a default I encode all my id's
var someUrl = servicesBaseUrl + servicesSomeService + encodedId + servicesSomeServiceBaseParms;
return $http.get(someUrl)
.then(function (response) {
var someArrayToReturnToTypeAhead = [];
return someArrayToReturnToTypeAhead;
})
.catch(function (ex) {
// Add error to a (localstorage based) queue for example which can be send later to the server when http becomes available.
$scope.showRequestError = true;
})
.finally(function () {
$scope.busyWithHttpRequest = false;
});
};