如何处理angular-ui-router解析中的错误 [英] How to handle error in angular-ui-router's resolve

查看:18
本文介绍了如何处理angular-ui-router解析中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 angular-ui-router 的 resolve 在进入状态之前从服务器获取数据.有时对服务器的请求失败,我需要通知用户失败.如果我从控制器调用服务器,我可以放置 then 并在其中调用我的通知服务,以防调用失败.我把对服务器的调用放在 resolve 中,因为我希望后代状态在它们开始之前等待服务器的结果.

如果对服务器的调用失败,我在哪里可以捕获错误?(我已阅读文档,但仍不确定如何阅读.另外,我正在寻找原因试试这个新的片段工具:)

"use strict";angular.module('MyApp', ["ui.router"]).config(["$stateProvider","$urlRouterProvider",函数($stateProvider,$urlRouterProvider){$urlRouterProvider.otherwise("/item");$stateProvider.state(列表",{网址:/项目",模板:'<div>{{listvm}}</div>'+'<a ui-sref="list.detail({id:8})">进入子状态并触发解析</a>'+'',控制器:[$scope",$state",函数($scope,$state){$scope.listvm = { state: $state.current.name };}]}).state("list.detail", {网址:/{id}",模板:'<div>{{detailvm}}</div>',解决: {数据:[$q",$timeout",函数($q,$timeout){var deferred = $q.defer();$超时(函数(){//deferred.resolve("成功");deferred.reject("失败");//这里解析失败}, 2000);返回 deferred.promise;}]},控制器:[$scope",data",$state",函数($scope,data,$state){$scope.detailvm = {状态:$state.current.name,数据:数据};}]});}]);

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script><script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script><div ng-app="MyApp"><ui-view/>

解决方案

问题是如果路由中的任何依赖解析被拒绝,控制器不会 被实例化.因此,您可以将故障转换为可以在实例化控制器中检测到的数据.

示例伪代码:-

 data: ["$q", "$timeout","$http", function ($q, $timeout, $http) {return $timeout(function () {//超时已经返回一个promise//返回是";//返回成功失败返回成功?{状态:真,数据:数据}:{状态:假};//从这里返回一个状态}, 2000);}]

并在您的控制器中:-

 控制器:["$scope", "data", "$state", function ($scope, data, $state) {//如果失败如果(!数据.状态){$scope.error = "一些错误";返回;}$scope.detailvm = {状态:$state.current.name,数据:数据};

如果您正在进行 $http 调用或类似调用,您可以使用 http promise 来始终解析数据,即使在失败的情况下也可以向控制器返回状态.

示例:-

解析:{数据:[$q",$timeout",$http",函数($q,$timeout,$http){返回 $http.get("someurl").then(function(){ return {status:true , data: "Yes"} },function(){ return {status:false} });//在失败的情况下捕获它并返回一个有效的数据以便控制器被实例化}]},

"use strict";angular.module('MyApp', ["ui.router"]).config(["$stateProvider","$urlRouterProvider",函数($stateProvider,$urlRouterProvider){$urlRouterProvider.otherwise("/item");$stateProvider.state(列表",{网址:/项目",模板:'<div>{{error}}</div><div>{{listvm}}</div>'+'<a ui-sref="list.detail({id:8})">进入子状态并触发解析</a>'+'',控制器:[$scope",$state",函数($scope,$state){$scope.listvm = { state: $state.current.name };}]}).state("list.detail", {网址:/{id}",模板:'<div>{{detailvm}}</div>',解决: {数据:[$q",$timeout",$http",函数($q,$timeout,$http){return $http.get("/").then(function(){ return {status:true , data: "Yes"} }, function(){ return {status:false} })}]},控制器:[$scope",data",$state",函数($scope,data,$state){$scope.detailvm = {状态:$state.current.name,数据:数据状态?数据:OOPS 错误"};}]});}]);

 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script><script data-require="angular-ui-router@*" data-semver="0.2.10" src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script><div ng-app="MyApp"><ui-view></ui-view>

I am using angular-ui-router's resolve to get data from server before moving to a state. Sometimes the request to the server fails and I need to inform the user about the failure. If I call the server from the controller, I can put then and call my notification service in it in case the call fails. I put the call to the server in resolve because I want descendant states to wait for the result from the server before they start.

Where can I catch the error in case the call to the server fails? (I have read the documentation but still unsure how. Also, I'm looking for a reason to try out this new snippet tool :).

"use strict";

angular.module('MyApp', ["ui.router"]).config([
  "$stateProvider",
  "$urlRouterProvider",
  function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/item");
    $stateProvider
    .state("list", {
      url: "/item",
      template: '<div>{{listvm}}</div>' +
      	'<a ui-sref="list.detail({id:8})">go to child state and trigger resolve</a>' +
        '<ui-view />',
      controller: ["$scope", "$state", function($scope, $state){
          $scope.listvm = { state: $state.current.name };
      }]
    })
    .state("list.detail", {
      url: "/{id}",
      template: '<div>{{detailvm}}</div>',
      resolve: {
        data: ["$q", "$timeout", function ($q, $timeout) {
          var deferred = $q.defer();
          $timeout(function () {
            //deferred.resolve("successful");
            deferred.reject("fail");   // resolve fails here
          }, 2000);
          return deferred.promise;
        }]
      },
      controller: ["$scope", "data", "$state", function ($scope, data, $state) {
        $scope.detailvm = {
          state: $state.current.name,
          data: data
        };
      }]
    });
  }
]);

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>

<div ng-app="MyApp">
  <ui-view />
</div>

解决方案

The issue is that if any of the dependencies in the route resolve is rejected, the controller will not be instantiated. So you could convert the failure to data that you can detect in the instantiated controller.

Example Pseudocode:-

   data: ["$q", "$timeout","$http", function ($q, $timeout, $http) {
      return $timeout(function () { //timeout already returns a promise
        //return "Yes";
        //return success of failure
         return success ? {status:true, data:data} : {status:false}; //return a status from here
       }, 2000);
     }]

and in your controller:-

 controller: ["$scope", "data", "$state", function ($scope, data, $state) {
      //If it has failed
      if(!data.status){
        $scope.error = "Some error";
       return;
      }
        $scope.detailvm = {
          state: $state.current.name,
          data: data
        };

If you are making an $http call or similar you can make use of http promise to resolve the data always even in case of failure and return a status to the controller.

Example:-

resolve: {
        data: ["$q", "$timeout","$http", function ($q, $timeout, $http) {
           return $http.get("someurl")
             .then(function(){ return {status:true , data: "Yes"} }, 
                    function(){ return {status:false} }); //In case of failure catch it and return a valid data inorder for the controller to get instantated
        }]
      },

"use strict";

angular.module('MyApp', ["ui.router"]).config([
  "$stateProvider",
  "$urlRouterProvider",
  function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/item");
    $stateProvider
    .state("list", {
      url: "/item",
      template: '<div>{{error}}</div><div>{{listvm}}</div>' +
      	'<a ui-sref="list.detail({id:8})">go to child state and trigger resolve</a>' +
        '<ui-view />',
      controller: ["$scope", "$state", function($scope, $state){
       $scope.listvm = { state: $state.current.name };
      }]
    })
    .state("list.detail", {
      url: "/{id}",
      template: '<div>{{detailvm}}</div>',
      resolve: {
        data: ["$q", "$timeout","$http", function ($q, $timeout, $http) {
           return $http.get("/").then(function(){ return {status:true , data: "Yes"} }, function(){ return {status:false} })
        }]
      },
      controller: ["$scope", "data", "$state", function ($scope, data, $state) {
   
    
        $scope.detailvm = {
          state: $state.current.name,
          data: data.status ? data :"OOPS Error"
        };
        
      }]
    });
  }
]);

 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    <script data-require="angular-ui-router@*" data-semver="0.2.10" src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
  <div ng-app="MyApp">
      <ui-view></ui-view>
    </div>

这篇关于如何处理angular-ui-router解析中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆