在AngularJS 1.3.8中添加一个运行块

Add a run block in AngularJS 1.3.8

本文关键字:一个 运行 添加 AngularJS      更新时间:2023-09-26

如何将run块添加到下面的AngularJS 1.3.8代码中

当我尝试在浏览器中加载应用程序时,FireFox调试器指示控制流在run块的第一行和另一个module/config/controllers的第一行短暂停止,而不进入其中的任何一行。然后程序在应用程序能够加载之前停止。相比之下,当我注释掉下面的run块时,Angular应用程序运行正常。

代码取自这个示例应用程序,唯一的变化是添加了run块。

angular.module('hello', [/*'ngCookies',*/ 'ngRoute' ]).config(function($routeProvider, $httpProvider) {
    $routeProvider.when('/', {
        templateUrl : 'home.html',
        controller : 'home',
        controllerAs : 'controller'
    }).otherwise('/');
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}).run(function ($rootScope, $cookies) {
    var cookieValue = $cookies.get("myCookie");
    if (cookieValue) {
        $rootScope.myCookieVar = cookieValue;
    }
}).controller('navigation',
function($rootScope, $http, $location, $route) {
    var self = this;
    self.tab = function(route) {
        return $route.current && route === $route.current.controller;
    };
    $http.get('user').then(function(response) {
        if (response.data.name) {
            $rootScope.authenticated = true;
        } else {
            $rootScope.authenticated = false;
        }
    }, function() {
        $rootScope.authenticated = false;
    });
    self.credentials = {};
    self.logout = function() {
        $http.post('logout', {}).finally(function() {
            $rootScope.authenticated = false;
            $location.path("/");
        });
    }
}).controller('home', function($http) {
    var self = this;
    $http.get('resource/').then(function(response) {
        self.greeting = response.data;
    })
});

$cookies在版本1.4之前没有get()set()方法。

参见文档

尝试更改为

var cookieValue = $cookies.myCookie;