简体   繁体   English

如何使用 Angular 1.5 版在 cookie 中存储和获取数组值

[英]How to store and get a array values in cookie with Angular version 1.5

I need to push value in array and stored in cookies when user click on GO button.当用户单击 GO 按钮时,我需要将值推送到数组中并存储在 cookie 中。

if value is more than 10 i need to remove the first added item in the array and updated cookies , displayed in front end.如果值大于 10,我需要删除数组中的第一个添加项和更新的 cookie,显示在前端。

but i'm tried multiple ways some time i am getting values sometimes not , the code is not consistently working.但有时我尝试了多种方法,但有时却没有得到值,代码无法始终如一地工作。

please find below the code请在代码下方找到

var cookieName = 'orderList';
$scope.orderList = $cookies.getObject(cookieName) || [];
$scope.saveCookie = function (val) {
    if ($scope.orderList.length >= 10) {
      $scope.orderList.shift();
    }

    $scope.orderList.push({productName: val}); 
    $scope.orderList = $cookies.putObject(cookieName,$scope.orderList);
  }

Note : I am using angular 1.5 and cookie 1.5 version .and i am getting console error .注意:我使用的是 angular 1.5 和 cookie 1.5 版本。我收到控制台错误。

http://plnkr.co/edit/K17uJv72U2ytG6JHZBtn?p=preview http://plnkr.co/edit/K17uJv72U2ytG6JHZBtn?p=preview

You didn't realize one thing.你没有意识到一件事。 The error only appears when you click the button the second time.该错误仅在您第二次单击该按钮时出现。 The reason why you're getting this error is the last line in your code-您收到此错误的原因是代码中的最后一行-

$scope.orderList = $cookies.putObject(cookieName,$scope.orderList);

when you replace it with -当您将其替换为 -

console.log(typeof $cookies.putObject(cookieName,$scope.orderList));

you'll get undefined in the console.你会在控制台中得到undefined And that is the catch.这就是问题所在。 When the function runs the second time, it is evaluating length of undefined , and hence, the error.当函数第二次运行时,它正在评估undefined length ,因此,错误。

Just replace the line with $cookies.putObject(cookieName,$scope.orderList) , because your $scope.orderList is already equal to the array with the new value pushed.只需用$cookies.putObject(cookieName,$scope.orderList)替换该行,因为您的$scope.orderList已经等于推入新值的数组。

EDIT: Updated Code编辑:更新代码

var cookieName = 'orderList';
$scope.saveCookie = function (val) {
    $scope.orderList = $cookies.getObject(cookieName) || [];
    if ($scope.orderList.length >= 10) {
      $scope.orderList.shift();
    }

    $scope.orderList.push({productName: val}); 
    $cookies.putObject(cookieName,$scope.orderList);
}

I brought the definition of $scope.orderList inside the function, since, in case the value of it is lost, it will reevaluate on each button click.我在函数中引入了$scope.orderList的定义,因为如果它的值丢失,它会在每次单击按钮时重新评估。 Its not crucial in all cases.它在所有情况下都不是至关重要的。 You might keep it out of the function, depending on your application flow.您可能会将其排除在函数之外,具体取决于您的应用程序流程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM