【问题标题】:Angularjs ngRoute redirect to "not found" page based on ajax dataAngularjs ngRoute根据ajax数据重定向到“未找到”页面
【发布时间】:2015-07-03 18:54:16
【问题描述】:

我在这里使用https://docs.angularjs.org/tutorial/step_07https://docs.angularjs.org/tutorial/step_08 中的示例进行演示。我们有以下路由:

phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: 'PhoneListCtrl'
      }).
      when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html',
        controller: 'PhoneDetailCtrl'
      }).
      otherwise({
        redirectTo: '/phones'
      });
  }]);

当我们转到链接 /phones/abcdefg 时,没有 json 文件与查询匹配,并出现一个空模板。在这种情况下,我们应该被重定向到“404 not found”页面。在实际情况下,例如,当我们去链接“/phones/:phoneId”但没有匹配的phoneId时,会返回如下所示的json。

{phoneIdMatch: false}

ng-route 中基于 ajax 数据重定向到页面的传统方式或最佳方式是什么?

【问题讨论】:

    标签: angularjs angular-ui-router ngroute angularjs-ng-route


    【解决方案1】:

    如果请求不存在的电话,一个好的 RESTful 后端会返回 404 响应。

    要处理该响应,您只需将错误回调添加到您的 $http 承诺:

    $http.get('phones/' + $routeParams.phoneId + '.json').then(function(response) {
      $scope.phone = response.data;
    }).catch(function(response) {
        // do what you want here
    });
    

    如果你想要去一个特定的路线,比如'/404',你可以使用 $location 服务:

    .catch(function(response) {
        if (response.status === 404) {
            $location.url('/404');
        }
    });
    

    【讨论】:

    • .success() 和 .error() 已弃用,请改用 .then() 和 .catch()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多