2015-10-05 75 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`