api获取请求,处理404

用户名

我正在研究处理来自api调用的404请求,在此情况下我将返回html。

$http.get('/api/house/' + $routeParams.id)
   .then(function (res) {

    $scope.houses = res.data;

}, function (err) {

    //when not found I am binding html from response
    if(err.status == 404){  
        $scope.errHtml = $sce.trustAsHtml(err.data);
    }

});

返回404的HTML:

<!doctype html>
<html>
<head>

   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" type="text/css" href="/resources/css/bootstrap.min.css">

   <title>404</title>

</head>
<body>

    <div>test 404</div>

</body>
</html>

鉴于我有:

<div ng-bind-html="errHtml"></div>

我试图了解这是否是从angular js的api调用处理404的最佳方法

穆罕默德·阿涅斯


处理angularjs中错误响应的最佳方法是编写一个$http interceptor只需编写一个拦截器服务并将其推送到$httpProvider拦截器,即可在一个地方处理所有错误。
请参阅此处的文档代码将如下所示

.factory('httpRequestInterceptor', function ($q, $location) {
    return {
        'responseError': function(rejection) {
            if(rejection.status === 404){
                $location.path('/404/');                    
             }
            return $q.reject(rejection);
         }
     };
});

然后,您可以将此服务注入interceptorconfig块中

.config( function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequestInterceptor');
});


您还可以在此处处理其他错误代码,并进行相应的重定向。希望这会有所帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章