javascript - 在使用 angularJS 更改路由之前提交函数

标签 javascript angularjs

我想提交一个http请求来检查每次路由更改时用户是否登录。 最新版本的 Angular(1.4.5)可以实现这一点吗?

我的路线是这样的:

// configure routes
app.config(['$routeProvider', function($routeProvider){
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl : 'directives/about.html',
            controller  : 'mainController'
        })

        // route for the home page
        .when('/login', {
            templateUrl : 'directives/login.html',
            controller  : 'loginContoller'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'directives/about.html',
            controller  : 'aboutController'
        })

        // route for the contact page
        .when('/contact', {
            templateUrl : 'directives/contact.html',
            controller  : 'contactController'
        });
}]);

最佳答案

如果你看the docs您将看到 when() 方法采用哪些参数。

route 参数是一个对象,并且有一个名为 resolve 的属性。 解析属性是应该解析的依赖关系的映射。

$routeProvider.when('/', {
    templateUrl: 'directives/about.html',
    controller: 'mainController',
    resolve: {
        loginCheck: function (myLoginCheckService) {
            return myLoginCheckService();//could return a $q.promise object.
        }
    }
});

resolve - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired.

AngularJS 文档

Look at the docs for more information.

关于javascript - 在使用 angularJS 更改路由之前提交函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32349513/

相关文章:

angularjs - Angular ui-router 在 ui-view 中重新加载整个应用程序

javascript - 如何调用 Angular Controller 中的函数?

javascript - 回调函数内的 Angular 形式验证 - Angular 1.2.5

javascript - node express 中的 app.post 和 app.use 有什么区别?

javascript - 在 Rails Asset Pipeline 中创建通用 javascript 函数

javascript - sailsjs 独立 Action 查看(Sailsjs V1.0.0)

angularjs - 基于 AngularJS 的 Web 应用程序的 Web UI 回归测试

javascript - Angular 2 : attaching string with property binding

javascript - 弹出而不是向下

javascript - AngularJS - 从指令获取属性值