2015-10-05 44 views
0

我有一个angularjs项目,我建立了一个ajaxService,它基本上围绕$http.post()。我想要实现的是一种简单的服务,在发生错误时创建警报,但覆盖.error()函数不应删除此警报(我希望它可以被调用,无论如何)。起初,我只是回复了$http.post()的承诺,但是当覆盖.error()时,删除了.error()服务的实施。Javascript Ajax Post封装

首先,我有这样实现:

this.Post = function (url, data) { 
    return $http.post(
     'Server/Server.php', 
     { 'url': url, 'data': data } 
    ) 
    .error(function (response) { 
     alertsService.RenderErrorMessage(response); 
    }); 
    } 

,但如果你再执行下面,RenderErrorMessage()将不会被调用(它的覆盖):

ajaxService.Post(ajaxUrlService.GetUserGroupsByUser(), { 'userId': userService.id }) 
     .error(function (response) { 
      userService.groups = response; 
     }); 

为了解决这个我试过以下:

this.Post = function (url, data) { 
    var obj = new Object(); 
    obj.success = function (response) {}; 
    obj.error = function (response) {}; 

    $http.post(
    'Server/Server.php', 
    { 'url': url, 'data': data } 
    ) 
    .success(function (response) { 
     if (typeof response == "String" && response.indexOf('xdebug-error') > 0) { 
      alertsService.RenderErrorMessage(response); 
      obj.error(response); 
     } 
     else { 
      obj.success(response); 
     } 
    }) 
    .error(function (response) { 
     alertsService.RenderErrorMessage(response); 
     obj.error(response); 
    }); 

    return obj; 
    } 

.Post()不返回在obj中,它返回'undefined'。这不是我所期望的,'undefined'的原因是什么,我该如何解决这个问题?

+1

签名是不正确...'后(网址,数据,[配置]); '参见文档 – charlietfl

+0

您的代码将返回undefined为obj,因为$ http.post是异步的。改为承诺。为了处理http请求中的错误,你可能需要考虑http拦截器。 – glennanthonyb

回答

1

如果我理解正确,您希望对服务中的错误执行一些特殊处理,但也允许在服务外部处理错误。

https://jsbin.com/bepozi/edit?html,js,console,output

示例 “换行” 的$http承诺与另一个承诺。 “内部承诺”执行一些特殊处理(写入控制台)。然后,AppController也可以通过将错误写入模型来执行自己的错误处理。

但是,对于http请求中的通用错误处理,我个人会使用http interceptor

+0

很好的例子。正如你所提到的,我正在寻找的是一个http拦截器。 –

1

考虑使用$ http拦截器,它允许您通过注册自己的处理程序来处理由$ http服务执行的请求和响应。

声明的拦截:

module.factory('myInterceptor', ['$log', function($log) { 
$log.debug('$log is here to show you that this is a regular factory with injection'); 

var myInterceptor = { 
    .... 
    .... 
    .... 
}; 

return myInterceptor; 

}]);

注册它:

module.config(['$httpProvider', function($httpProvider) { 
$httpProvider.interceptors.push('myInterceptor'); 

}]);

在这里阅读更多:http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/为`$ http.post`