无法使用Angular将数据保存到localStorage

时间:2016-06-26 07:32:43

标签: javascript angularjs local-storage

朋友们,我是角色新手,想要创建单页应用程序。

我的代码在创建产品列表时工作正常,当点击产品时我将登陆到详细信息页面,但是现在我想显示另一个列表,它将显示已经查看的产品。

我盯着挖掘出解决方案并想出了一些想法,通过使用ProductId$routePrams推送到某个数组中,这是正常工作直到用户重新加载页面,因为重新加载页面后所有已保存ProductId从数组中消失了。我也尝试将数据保存到本地存储但是失败然后来这里寻求帮助...请检查下面的代码并请建议他们是否有任何其他方法来破解这个狗屎

controller.js

var myApp = angular.module('assignment', ['ngRoute']);



var viewedProducts = []; // created a global empty array
var uniqueNames = [];  // created second global empty array


myApp.config(['$routeProvider',function($routeProvider) {
  $routeProvider.when('/',{
      templateUrl : 'list/list.html'
    })
  .when('/:productId',{ // Passing productId 
    templateUrl : 'detail/detail.html'
  })

}])

myApp.service('myData', ['$http', function($http){
  return{
    itemList : function(){
      return $http({'method': 'GET', 'url' : 'js/data.json'}).then(function(response){
        return response.data;
      }, function(data){
        console.log(data);
      })
    }
  }
}])

myApp.controller('itemData', ['$scope','$http', 'myData', function($scope, $http, myData){

  myData.itemList().then(function(data){
    $scope.items = data;

  }, function(){
    console.log(data);
  })



}])

myApp.controller('details', ['$scope', '$http', '$routeParams', 'myData', function($scope, $http, $routeParams, myData){
  $scope.product = $routeParams; // Getting Product Id using $routeParams


  myData.itemList().then(function(data){


    angular.forEach(data, function(value, key){ 

      if(value.productId == $routeParams.productId) {
        $scope.product = value; 


        viewedProducts.push(value.productId);

        /*Trying to same data to localStorage*/
        localStorage.setItem('viewedItems', viewedProducts);
        var getViewed = localStorage.getItem('viewedItems');
        getViewed = getViewed.split(',')

        angular.forEach(getViewed, function(value, key){
            if(uniqueNames.indexOf(viewedProducts[key]) === -1) {
              uniqueNames.push(viewedProducts[key]);
            }
        });
      }

    });

  });

}])

myApp.controller('viewedProducts', ['$scope', '$http', '$routeParams' , 'myData', function($scope, $http, $routeParams, myData){

$scope.viewed = [];

  myData.itemList().then(function(data){
    //$scope.items = data
    angular.forEach(data, function(datavalue, datakey){

      angular.forEach(uniqueNames, function(value, key){
        if (datavalue.productId == uniqueNames[key] && datavalue.productId !== $routeParams.productId) {
          $scope.viewed.push(datavalue);
        }
      });

    });
  })

}])

4 个答案:

答案 0 :(得分:0)

$ window.localStorage.setItem(键,值)

localStorage仅支持字符串,因此您需要使用JSON.stringify()对数组进行字符串化。

这是in-depth solution

或者您可以使用角度模块,例如angular-localstorage

答案 1 :(得分:0)

因为localstorage仅支持字符串作为值。

因此存储数据使用

var getViewed = JSON.parse(localStorage.getItem('viewedItems'));

用于重新使用数据

Private Sub btnIUK_Click()

Dim arrLstBox()
Dim rng, FoundCell, tmpCell As Range
Dim i, j, numRows, lastColumn, lastRow As Long
Dim FirstAddress, searchFor, colWidth As String

Set rng = ActiveSheet.UsedRange
numRow = 0

With rng

    lastRow = .Rows.Count
    lastColumn = .Columns.Count

End With

Me.ListBox1.ColumnCount = lastColumn
Me.ListBox1.ColumnWidths = "60;70;190;40;90;90;70;80;50;60;90;120;5"


    Set FoundCell = rng.Find(what:="!UKINADMISSIBLE", LookIn:=xlValues, lookat:=xlWhole)

    If Not FoundCell Is Nothing Then _
    FirstAddress = FoundCell.Address

    Do Until FoundCell Is Nothing

        Set FoundCell = rng.FindNext(after:=FoundCell)

        If FoundCell.Address = FirstAddress Then
            numRow = numRow + 1
            Exit Do
        ElseIf FoundCell.Row <> rng.FindNext(after:=FoundCell).Row Then
            numRow = numRow + 1
        End If

ReDim arrLstBox(1 To numRow + 1, 1 To lastColumn + 1)

Loop

Do Until FoundCell Is Nothing

    For i = 1 To numRow
        For j = 1 To lastColumn

            If Not IsEmpty(Cells(FoundCell.Row, j).Value) Then

                arrLstBox(i, j) = Cells(FoundCell.Row, j).Value

            End If


        Next j

        Set FoundCell = rng.FindNext(after:=FoundCell)

        If FoundCell.Address = FirstAddress Then _
            Exit For

    Next i

    If FoundCell.Address = FirstAddress Then _
            Exit Do

Loop

Me.ListBox1.List = arrLstBox()----->ERROR

lastRow = ListBox1.ListCount
MsgBox "Records Found = " & lastRow, vb, "Inadmissibles On UK Sectors"

End Subode here

答案 2 :(得分:0)

即使我遇到类似的问题,我也会使用ngStorage来提供$localStorage and $sessionStorage两种服务。

您可以像这样定义

controller('savedata', function($scope, $localStorage) {
  $scope.$storage = $localStorage.$default({
    x: 42
   });
});

以下是Plnkr

希望它适合你:)

答案 3 :(得分:0)

更新了myData服务以利用存储空间, 请检查一下是否有效,

myApp.service('myData', ['$http', '$window', '$q', '$timeout', function($http, $window, $q, $timeout) {
    var storage = $window.localStorage;

    return {
        itemList: function() {
            var deferred = $q.defer(),
                list = storage.getItem('item-list');

            if (list) {
                $timeout(function() {
                    deferred.resolve(angular.toJson(list));
                });
            } else {

                $http({ 'method': 'GET', 'url': 'js/data.json' })
                    .then(function(response) {
                            storage.setItem('item-list', angular.fromJson(response.data));
                            deferred.resolve(response.data);
                        },
                        function(data) {
                            console.log(data);
                            deferred.reject(data);
                        });
            }

            return deferred.promise;
        }
    }
}]);