AngularJS - routeProvider决心调用服务的方法 [英] AngularJS - routeProvider resolve calling a service method

查看:109
本文介绍了AngularJS - routeProvider决心调用服务的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了检查用户的登录状态的服务(登录,如果令牌中存在用户,否则重定向到登录页面)。

I've created a service which checks the user login state (log the user in if token exists, otherwise redirect to login page).

本来我打电话通过routeProvider解决这个服务 - 这工作完全一次,但由于Angularjs服务是单身测试不会连续通话运行

Originally I called this service through the routeProvider resolve - this works perfectly once, but since Angularjs services are singleton the test would not run for consecutive calls.

然后我试图测试移动到一个方法返回的对象之内,但是我似乎无法将包拿到routeProvider决心调用服务的具体方法(这是有意义的方式)。

I then tried to move the test into a method within the returned object, but I can't seem to be bale to get the routeProvider resolve to call a specific method of a service (which makes sense in a way).

问题是,我如何确保我的测试,每个路径被加载时执行的?

Question is, how do I make sure my test is executed each time the route is loaded?

在理论家的视频系列( http://www.egghead.io/video/rbqRJQZBF3Q )他用的是功能分配给控制器,但是这似乎并不像一个生产应用的解决方案(我不想要一个功能分配给特定的控制器和我相信Angularjs依赖注入将无法正常工作)。

In the egghead videos series (http://www.egghead.io/video/rbqRJQZBF3Q) he uses a function assigned to the controller but this doesn't seem like the right solution for a production app (I don't want to assign a function to a specific controller and I do believe the Angularjs dependency injection won't work).

推荐答案

的服务是单身意味着有初始化只有一个,但时间,但如果你只是从服务回报它会被调用一次,但如果你从服务中返回一个函数它将一次又一次地叫。看到下面的示例对工作

service are singletons means there are initialized only one but time but if you simply return from service it will be called one time but if you return a function from service it will be called again and again .See Below Sample for working

var app = angular.module('ajay.singhApp', [])
  .config(['$routeProvider', function($routeProvider) {
    $routeProvider
      .when('/view1', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        resolve: {
            myVar: function (repoService) {
                return repoService.getItems().then(function (response) {
                    return response.data;
                });
            }
        }
      })
        .when('/view2', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
      .otherwise({
        redirectTo: '/view1'
      });
  }]);


app.factory('repoService', function ($http) {
    return {
        getItems: function () {
            return $http.get('TextFile.txt');
        }
    };
});

这篇关于AngularJS - routeProvider决心调用服务的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆