gpt4 book ai didi

javascript - 每次加载单页应用程序时检索 cookie

转载 作者:行者123 更新时间:2023-12-03 06:29:15 25 4
gpt4 key购买 nike

需要对下面的 AngularJS 代码进行哪些具体更改,以在每次加载页面时检查名为 myCookie 的 cookie 是否存在,然后设置 $rootScope.myCookieValue 变量成为 myCookie 的值?

代码来自 the sample app whose complete code you can explore at this link 。这是一个非常简单的示例应用程序,我只想要一个简单的工作解决方案,以便我可以从中构建更复杂的方法。

angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider, $httpProvider) {

$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'home',
controllerAs : 'controller'
}).otherwise('/');

$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';

}).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;
})
});

最佳答案

我猜你可以在运行 block 中做到这一点:

 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';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';

}).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;
})
});

我认为你应该使用 Angular 版本> 1.4.x

您还应该添加引用 angular-cookies.js

关于javascript - 每次加载单页应用程序时检索 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38512328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com