Javascript 如何实现angularjs异步?
我使用的是AngularJS v1.5.8,我的要求是,当我点击下一步按钮时,它会在按钮内显示“Processing…”作为文本,在完成操作之前,我已经将$q包含在我的服务中,以获得异步设施,但不起作用。请看我下面的代码 服务Javascript 如何实现angularjs异步?,javascript,angularjs,Javascript,Angularjs,我使用的是AngularJS v1.5.8,我的要求是,当我点击下一步按钮时,它会在按钮内显示“Processing…”作为文本,在完成操作之前,我已经将$q包含在我的服务中,以获得异步设施,但不起作用。请看我下面的代码 服务 mainApp.factory('PINVerificationServices', ['$http', '$rootScope','$q', function ($http, $rootScope) { return { IsPermitted:
mainApp.factory('PINVerificationServices', ['$http', '$rootScope','$q', function ($http, $rootScope) {
return {
IsPermitted: function (param) {
return $q($http({
url: '/Api/ApiPINVerification/IsPermitted/' + param,
method: 'POST',
async: true
}));
}
};
}]);
控制器
mainApp.controller('PINVerificationController', function ($scope, $rootScope, $state, $window,$q, PINVerificationServices) {
$scope.SubmitText = "Next";
$scope.Next = function () {
$scope.SubmitText = "Processing...";
PINVerificationServices.IsPermitted($scope.PIN).then(function (result) {
$scope.SubmitText = "Next";
});
}
}
HTML
<div class="list-group list-group-sm">
<div class="list-group-item">
<input class="form-control" ng-model="PIN" placeholder="PIN" required id="PIN" name="PIN" type="text" />
</div>
</div>
<button type="submit" ng-click="Next()">{{SubmitText}}</button>
{{SubmitText}}
试试这个:
return $http({
method: 'POST',
url: '/Api/ApiPINVerification/IsPermitted/' + param
});
进行以下更改(根据您对嵌套$http
的要求)
在工厂中仅使用$http
,并且不需要$rootScope
,应该如下所示:
mainApp.factory('PINVerificationServices', ['$http', function ($http) {
return {
IsPermitted: function (param) {
return $http({
url: '/Api/ApiPINVerification/IsPermitted/' + param,
method: 'POST'
});
},
GetStudentInformationByPIN : function () {
return $http({
url: '/Api/ApiPINVerification/GetStudentInformationByPIN /',//your api url
method: 'GET'
});
}
};
}]);
在控制器中使用$q.all()
:
但不起作用
-您尝试过最简单的调试吗?比如检查开发者工具控制台和网络选项卡?他们为真正的开发者提供了很多信息。我检查了@JaromandaX,它给出的$q不是定义错误。谢谢我已将$q包含在我的服务中
-对。。。您是否在页面中包含了q库?在工厂中注入$q
,例如:函数($http,$rootScope,$q)
$q
在那里根本不需要,因为$http
已经返回了一个承诺。。删除$q
函数包装器应该可以解决您的问题@Sergaroscan不工作您可以显示console.log(PINVerificationServices.IsPermitted($scope.PIN))的输出,但另一个问题是,不使用嵌套的http服务调用。假设您首先调用了IsPermitted($scope.PIN)函数,然后再次调用IsPermitted($scope.PIN)函数中的另一个函数PINVerificationServices.GetStudentInformation ByPin($scope.PIN)。不要嵌套这些调用。只需将调用放在一个函数中,该函数来回传递变量,直到您验证了用户。
mainApp.controller('PINVerificationController', function ($scope, $rootScope, $state, $window,$q, PINVerificationServices) {
$scope.SubmitText = "Next";
$scope.Next = function () {
$scope.SubmitText = "Processing...";
$q.all([PINVerificationServices.IsPermitted($scope.PIN),
PINVerificationServices.GetStudentInformationByPIN($scope.PIN),
//other promises
]).then(function (result) {
if(result[0].data){
$scope.SubmitText = "Next";
}
if(result[1].data){
// studentdata response handling
}
});
}
}