AngularJS $ routeChangeError未被调用或执行

时间:2015-08-06 16:21:44

标签: angularjs routing single-page-application angularjs-routing

在控制器加载和我的视图呈现之前,我在路由器中进行了一些API调用。这是我正在尝试的:

app.js:

site biomass index

1     0.001 1.5

2    0.122  2.3

3    0.255  4.9

这在没有错误时有效。我想抓住错误并尝试过:

设置控制器:

.when('/settings', {
    templateUrl: 'views/settings.html',
    controller: 'SettingsController',
    resolve: {
      avatars: function() {
        return APIProvider.$get().getAvatars();
      },
      householdData: function() {
        return APIProvider.$get().getHousehold();
      }
    }
  })

但这似乎没有触发。以下是我正在尝试使用的docs

FWIW,以下是API调用的示例:

$rootScope.$on("$routeChangeError", function () {
    $location.path('/signin', false);
});

===========什么工作=============

这在app.js中起作用,但我对“更好”或更“有棱角”的解决方案持开放态度:

var service = this;

/**
 * @ngdoc function
 * @name API#doRequest
 * 
 * @description
 * utility function to handle $http actions. returns a promise
 */
function doRequest(path, method, data, opts) {
    var def = $q.defer(),
        args = [];

    if(['get','delete','post'].indexOf(method) === -1) { return def.reject();    }

    args.push(getUrl(path));
    if(data) { args.push(data ); }

    $http[method].apply(this, args)
        .success(function(data){
            def.resolve(data);
        })
        .error(function(){

            def.reject({ 'title': 'Connection problem.', 'subtitle': 'Please try your request again in a moment.'});
        });
    return def.promise;
}

 /**
 * @ngdoc function
 * @name API#getHousehold
 * 
 * @description
 * requires access token in Household
 * returns promise with array of Households from server (should be only one)
 */
service.getHousehold = function() {
    // needs Household to have access token to work
    var def = $q.defer();

    if (typeof(Household.getAccessToken()) === 'undefined') {
        def.reject('Incorrect household id.');
        return def.promise;
    } else {
        var path = 'household/';
        return doRequest(path, 'get');
    }
};

0 个答案:

没有答案