使用 Ionic 的本地存储

Posted

技术标签:

【中文标题】使用 Ionic 的本地存储【英文标题】:Local storage using Ionic 【发布时间】:2015-11-02 15:47:21 【问题描述】:

我正在尝试将我的应用程序连接到本地存储,以便我可以将数据保存在用户设备上,并且不会在每次应用程序关闭时重置。我唯一的问题是我无法弄清楚将本地存储实际链接到我的对象数组。任何帮助是极大的赞赏。我添加了任何我认为相关的代码。

app.js

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('gas-mileage-tracker', ['ionic', 'ionic.utils', 'gas-mileage-tracker.controllers', 'gas-mileage-tracker.services'])

.run(function($ionicPlatform) 
  $ionicPlatform.ready(function() 
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) 
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    
    if (window.StatusBar) 
      // org.apache.cordova.statusbar required
      StatusBar.styleLightContent();
    
  );
)
.run(function($localstorage) 
      var mileages = [];
      $localstorage["mileages"] = JSON.stringify(mileages);
      $localstorage.set('name', 'mileages');
      console.log($localstorage.get('name'));
      $localstorage.setObject('post', mileages=[
        id: 0,
        mpg: 20,
        car: "1998 Toyota 4runner",
        miles_driven: "",
        gallons_added: "",
        gas_station: "Shell"
      ]);
      var post = $localstorage.getObject('post');
      console.log(post);

    )
.config(function($stateProvider, $urlRouterProvider) 

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider

  // setup an abstract state for the tabs directive
    .state('tab', 
    url: '/tab',
    abstract: true,
    templateUrl: 'templates/tabs.html'
  )

    .state('tab.calculations', 
      url: '/calculations',
      views: 
        'tab-calculations': 
          templateUrl: 'templates/tab-calculations.html',
          controller: 'CalculationsCtrl'
        
      
    )

    .state('tab.mileages', 
      url: '/mileages',
      views: 
        'tab-mileages': 
          templateUrl: 'templates/tab-mileages.html',
          controller: 'MileagesCtrl'
        
      
    )

    .state('tab.mileage-details', 
      url: '/mileages/:mileageId',
      views: 
        'tab-mileages': 
          templateUrl: 'templates/mileage-details.html',
          controller: 'MileageDetailsCtrl'
        
      
    )

    .state('tab.gas_stations', 
      url: '/gas_stations',
      views: 
        'tab-gas_stations': 
          templateUrl: 'templates/tab-gas_stations.html',
          controller: 'GasStationsCtrl'
        
      
    )

    .state('tab.cars', 
      url: '/cars',
      views: 
        'tab-cars': 
          templateUrl: 'templates/tab-cars.html',
          controller: 'CarsCtrl'
        
      
    )


    $urlRouterProvider.otherwise('/tab/mileages');

);

controllers.js

angular.module('gas-mileage-tracker.controllers', [])

.controller('CalculationsCtrl', function($scope, Mileages) 
    $scope.add = function(mileage) 
        Mileages.add(mileage);
    
)
.controller('MileagesCtrl', function($scope, Mileages) 
    $scope.mileages = Mileages.all();
    $scope.remove = function(mileage) 
        Mileages.remove(mileage);
    ;
    $scope.add = function(mileage) 
        Mileages.add(mileage);
    ;

)
.controller('MileageDetailsCtrl', function($scope, $stateParams, Mileages) 
    $scope.mileage = Mileages.get($stateParams.mileageId);
)

.controller('GasStationsCtrl', function($scope, $stateParams, Mileages) 
    $scope.mileages = Mileages.all();
    $scope.mileage = Mileages.get($stateParams.mileageId);
)

.controller('CarsCtrl', function($scope, $stateParams, Mileages) 
    $scope.mileages = Mileages.all();
    $scope.mileage = Mileages.get($stateParams.mileageId);
)

services.js

angular.module('gas-mileage-tracker.services', [])

.factory('Mileages', function() 
    var mileages = [
    id: 0,
    mpg: 20,
    car: "1998 Toyota 4runner",
    miles_driven: "",
    gallons_added: "",
    gas_station: "Shell"
  , 
    id: 1,
    mpg: 16,
    car: "2002 Toyota 4runner",
    miles_driven: "",
    gallons_added: "",
    gas_station: "Loaf N' Jug"
  , 
    id: 2,
    mpg: 18,
    car: "2002 Toyota 4runner",
    miles_driven: "",
    gallons_added: "",
    gas_station: "Conoco"

  , 
    id: 3,
    mpg: 17,
    car: "1998 Toyota 4runner",
    miles_driven: "",
    gallons_added: "",
    gas_station: "Bradley"
  , 
    id: 4,
    mpg: 18,
    car: "2002 Toyota 4runner",
    miles_driven: "",
    gallons_added: "",
    gas_station: "Texaco"
  ];

  return 
    all: function() 
      return mileages;
    ,
    remove: function(mileage) 
      mileages.splice(mileages.indexOf(mileage), 1);
    ,
      add: function(mileage) 
        mileage.id = mileages.length;
        mileage.mpg = mileage.miles_driven/mileage.gallons_added
        mileages.push( 
          editMode: false, 
          id: mileage.id, 
          mpg: mileage.mpg, 
          car: mileage.car,
          gas_station: mileage.gas_station
           ); 
          console.log(mileage); // Log the original mileage 
        console.log(mileages[mileage.id]); // Log the added mileage 
        mileage.mpg= ''; 
        mileage.miles_driven= ''; 
        mileage.gallons_added= ''; 
        mileage.car= ''; 
        mileage.gas_station= '';

    ,
    edit: function(mpg) 
      mileage.editMode = true;
      mileages.mpg = mileage.mpg
      console.log(mileage);
    ,
    save: function(mpg) 

        mileage.editMode = false;
    ,
    get: function(mileageId) 
      for (var i = 0; i < mileages.length; i++) 
        if (mileages[i].id === parseInt(mileageId)) 
          return mileages[i];
        
      
      return null;
    
  ;
);

utils.js

angular.module('ionic.utils', [])

.factory('$localstorage', ['$window', function($window) 
  return 
    set: function(key, value) 
      $window.localStorage[key] = value;
    ,
    get: function(key, defaultValue) 
      return $window.localStorage[key] || defaultValue;
    ,
    setObject: function(key, value) 
      $window.localStorage[key] = JSON.stringify(value);
    ,
    getObject: function(key) 
      return JSON.parse($window.localStorage[key] || '');
    
  
]);

【问题讨论】:

问题的范围很广,请说明您要完成什么? 我希望能够使用我目前拥有的功能将删除和不添加到数据库中。 【参考方案1】:

使用此服务来管理、创建、检索或删除其每个控制器中的 LocalStorage 变量。我希望它会有所帮助。

.factory('sessionService',['$http',function($http)
return 
   set:function(key,value)
      return localStorage.setItem(key,JSON.stringify(value));
   ,
   get:function(key)
     return JSON.parse(localStorage.getItem(key));
   ,
   destroy:function(key)
     return localStorage.removeItem(key);
   ,
 ;
])

【讨论】:

好的,那么我该如何使用我目前拥有的添加和删除功能来实现它? @JacobBrauchler 嘿,我不太明白你的意思 我似乎无法使用这些方法使其工作,我需要保存某些数据,但我无法使用这些功能来做到这一点。 某些作品?你的意思是?那个格式有那个数据? 根据我现有的服务,我尝试在您提供给我的功能中实现它们,但是没有存储数据。这将是您在我的 services.js 中看到的里程格式【参考方案2】:

只是为了确保让更多用户了解一个事实,即本地存储不一定必须是持久的(在 ios 上),请查看:

How permanent is local storage on android and iOS?

因此,我建议您在包装器中使用 nativestorage:

https://github.com/TheCocoaProject/cordova-plugin-nativestorage

【讨论】:

以上是关于使用 Ionic 的本地存储的主要内容,如果未能解决你的问题,请参考以下文章

Ionic 3 本地存储中的数组

Ionic/Angular:在本地存储中读写数组

从 ionic2 本地存储中删除数组

Cordova/Phonegap/Ionic App - 远程图像的本地存储

ionic 3 中的本地存储和选项卡菜单

Ionic 媒体插件无法在 iOS 上播放本地存储的 mp3 文件