【问题标题】:AngularJS: Recommendation on rendering different view when HTTP 404AngularJS:关于在 HTTP 404 时呈现不同视图的建议
【发布时间】:2014-06-04 01:15:15
【问题描述】:

我在做什么

  • 我正在尝试创建一项服务来加载当月的用户预算。代码看起来像

    $scope.thisMonthBudgetSummary = function () { console.log('检索预算摘要');

        var date = new Date();
        BudgetSummary.get({'month': date.getMonth() + 1, 'year': date.getFullYear()},
            function () {
                // success
            },
            function (error) {
                //error
                console.log('error:', error.status);
            })
    };
    

问题
- 当 HTTP 响应为 404 时,我想在单页上呈现不同的视图,对此有何建议?我很困惑
- 我认为在 Controller 中硬编码模板名称不是一个好主意

【问题讨论】:

  • 如果您不想硬编码模板名称,我认为您应该重定向到 404 路由

标签: angularjs angularjs-scope angularjs-service angularjs-routing


【解决方案1】:

$http 拦截器当然是一种方式,在您的应用程序配置中您可以这样做:

$httpProvider.interceptors.push(['$q', '$location', function ($q, $location) {
                return {
                    'request': function (config) {
                        return config || $q.when(config);
                    },
                    'requestError': function (rejection) {
                        return $q.reject(rejection);
                    },
                    'response': function (response) {
                        return response || $q.when(response);
                    },
                    'responseError': function (rejection) {
                        if (rejection.status == "404") {
                           $location.path("/yourErrorRoute")
                        }
                        return $q.reject(rejection);
                    }
                };
}])

【讨论】:

    【解决方案2】:

    如果您希望在您的应用程序中使用默认功能,@Mohammad Sepahvand 的回答很有效。如果您只是想要一次性完成该请求,您可以这样做:

    var date = new Date();
    BudgetSummary.get({'month': date.getMonth() + 1, 'year': date.getFullYear()},
        function (data, status, headers, config)  {
            //check your status here-->
            if (status === '200'){
                $location.path('/path/to/other/route');
            }
        },
        function (data, status, headers, config){
            //check your status here-->
            if (status === '404'){
                $location.path('/path/to/other/route');
            }
        })
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 2015-01-03
      • 2014-03-14
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多