如何使失败的路由解析承诺加载不同的模板URL

How to make a failed routing resolve promise load a different template URL?

本文关键字:加载 URL 失败 何使 路由 承诺      更新时间:2023-09-26

学习Angular并遇到一个我似乎找不到"好"答案的问题。我一直在遵循官方教程,在我正在进行的项目中也有类似的设置。

$routeProvider.when case for phone details会根据在电话列表页面中单击的电话名称获取一个特定的.JSON文件。问题是,如果您键入的电话名没有与之关联的.JSON文件,那么路由仍然会继续,并显示一个空白页面。我正在想办法防止这种情况发生。

我已经下定决心要在什么时候走。但是,我只能阻止视图更改或使用$location.path重定向。这两者似乎都不理想。

如何为并没有JSON文件的手机显示"404页面"视图?在我的脑海中,如果GET请求以404响应,但似乎无法使其工作,我会显示一个不同的templateUrl。

任何帮助都会很棒!

这是我目前掌握的代码:

我的路线处理。

.when('/game/:Game', {
    templateUrl: 'views/game-detail.html',
    controller: 'GameDetailCtrl',
    resolve: {
      myData: ["Games", "$location", "$q", "$timeout",'$rootScope', function(Games, $location, $q, $timeout,$rootScope) {
        var def = $q.defer();
        var path = $location.path().toString().substring(6);
          // Games service
         Games.get({gameName: path}, function(game, s) {
          }).$promise.then(
            function(data) {
              // found game data 
              def.resolve(data);
            },
            function(error) {
              // couldn't find JSON file
              def.reject(error);
            }
          );
        return def.promise;
      }]
    }
  }).when('/pageNotFound', {
    templateUrl: 'views/error.html'
  })

根作用域路由更改错误侦听器:

 $rootScope.$on("$routeChangeError",
  function(event, current, previous, rejection) {
    console.log("failed to change routes");
    //$location.path('/pageNotFound');
  });

好吧,你真的不是这样做的,在这种情况下,你要做的是让你的模板HTML包含成功和失败场景的模板,以及在调用失败或成功时切换状态的ng开关。

此外,我认为如果你也试图从指令中复制这个想法,那也会奏效:Angular.js指令动态模板URL

您可以尝试使用以下代码更改路径:

        function(error) {
          // couldn't find JSON file
          $location.path('/pageNotFound');
        }