( function() {
angular.module('foo')
.factory('someFac', function ($injector, $http, $q){
var temp;
$http.get('url').then(function(response){ //implement $q to wait for this to finish
if(response === 1){
temp = 1
else{
temp = 2
});
return $injector.get(temp);
}());
如何在返回之前实现$ q以使promise得到解决?
答案 0 :(得分:0)
虽然http确实会返回一个承诺,但您可以按原样处理结果并使用$ q库:
( function() {
angular.module('foo')
.factory('someFac', function ($injector, $http, $q){
var temp;
var deferred = $q.defer();
$http.get('url').then(function(response){ //implement $q to wait for this to finish
if(response === 1){
deferred.resolve(1);
else{
deferred.reject(2);
});
return deferred.promise;
}());
您可以通过延迟对象拒绝或解析并传递必要的数据。
答案 1 :(得分:-1)
您在app.js文件中添加此代码,您不需要从服务器端抛出异常,只需在异常中添加代码,就像
一样public ActionResult YourMethodName(string emailAddress)
{
BasicResponse Response = new BasicResponse();
try
{
// do your work here
}
catch (Exception ex)
{
Response.ErrorKey = ex.Message;
Response.ErrorCode = (int)HttpStatusCode.BadRequest;
}
return Json(Response, JsonRequestBehavior.AllowGet);
}
它自动捕获$ q服务,您可以在服务器代码中添加所需的错误代码并在此处映射到交换机
angular.module('foo').factory('responeInterceptor', ['$q', '$window', '$injector', 'NotificationService', function ($q, $window, $injector, notifyService) {
return {
'response': function (response) {
// do something on success
return response;
},
//in case of Error
'responseError': function (rejection) {
switch (rejection.status) {
case 400:
notifyService.notifyError(rejection.data.errorKey);
break;
case 403:
$window.location.href = '/Logout';
break;
default:
}
return $q.reject(rejection);
}
};
}]);