Giter VIP home page Giter VIP logo

angular-stored-object's Introduction

angular-stored-object

Build Status

Local resource support for Angular using HTML5 storage

Combines the best of ngResource, ngStorage and angular-local-storage to give you access to local and session storage within Angular, but also provides a storage strategy that supports sharing sessionStorage data between multiple tabs via transient localStorage use.

Installation

Using NPM:

npm install --save angular-stored-object

Using Bower:

bower install --save angular-stored-object

API

The small API is fully documented.

Example

A session service consists of an object that when stored will be identified via the prefixed key 'session':

  angular
    .module('auth', ['yaacovCR.storedObject']);
    
  angular
    .module('auth')
    .factory('session', session);

  function session(ycr$StoredObject) {
    return new ycr$StoredObject('session');
  }

An auth service manipulates the properties of the session object and calls $create and $delete as needed to persist to/delete from storage. $update, not shown, can be used when the token needs to be refreshed.

  angular
    .module('glass.auth')
    .factory('auth', auth);

  function auth($http, $state, backendURI, session) {
    
    var _redirectToState = null;
    var _redirectToParams = null;
    
    return {
      login: login,
      isLoggedIn: isLoggedIn,
      logout: logout,
      registerRedirect: registerRedirect,
      followRedirect: followRedirect
    };
    
    function login(credentials) {
      return $http.post(backendURI + '/login', { credentials: credentials }).then(function(result) {
        session.token = result.data.token;
        session.loggedInUser = result.data.user;
        session.$create('sessionStorageWithMultiTabSupport');
      });
    }
    
    function isLoggedIn() {
      return !!session.token;
    }
    
    function logout() {
      session.$delete();
      $state.transitionTo('login');
    }
    
    function registerRedirect(toState, toParams) {
      _redirectToState = toState;
      _redirectToParams = toParams;
    }
    
    function followRedirect() {
      if (_redirectToState) {
        $state.transitionTo(_redirectToState, _redirectToParams);
        _redirectToState = _redirectToParams = null;
      } else {
        $state.transitionTo('home');
      }      
    }

For completion, the run block:

  angular
    .module('glass')
    .run(runBlock);

  function runBlock($rootScope, $state, $timeout, auth) {
    $rootScope.$on('$stateChangeStart', onStateChangeStart);
    $rootScope.$on('storedObject:session:externalChange', onSessionChange);
    
    function onStateChangeStart(event, toState, toParams) {
      if (toState.name === 'login' && auth.isLoggedIn()) {
        event.preventDefault();
        auth.followRedirect();
      }
      if (toState.data && toState.data.authenticate && !auth.isLoggedIn()) {
        event.preventDefault();
        auth.registerRedirect(toState, toParams);
        $state.transitionTo('login');
      }
    }
        
    function onSessionChange() {
      $timeout(function() {
        $state.reload();
      });
    }

  }

And the routes:

  angular
    .module('glass')
    .config(routerConfig);

  function routerConfig($stateProvider, $urlRouterProvider) {

    $stateProvider

      .state('home', {
        url: '/',
        templateUrl: 'app/main/main.html',
        controller: 'MainController',
        controllerAs: 'main',
        data: {
          authenticate: true
        }
      })

      .state("login", {
        templateUrl: "app/components/login/login.route.html"
      });
    
    $urlRouterProvider.otherwise('/');
  }

angular-stored-object's People

Contributors

yaacovcr avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

angular-stored-object's Issues

Feature Request: setDefaultStrategy then createOrUpdate

as discussed with Yaacov:

In theory, a combined method could be used that creates
or updates as necessary and use a default storage strategy, that is perhaps
specified when the service is created. I think this is a reasonable feature
request, especially useful when the storage strategy is not likely to
change.

_setup and __loadIntoMemory are inconsistent

in _loadIntoMemory method, we have
_storageType = (_storageStrategy === 'localStrategy') ? 'localStorage' : 'sessionStorage';
while in _setup we have
_storageType = (storageStrategy === 'localStorage') ? 'localStorage' : 'sessionStorage';

I think this 'localStrategy' in loadIntoMemory is messing with things, and so it results after a reload in having in sessionStorage things meant to be in localStorage

get from local storage at application start

Hello,

This project is very promising, but I think it miss one main use case of local storage : to be able to get back information from previous session when starting the application.

$create should not check the key is not yet used, and instanciate the value with what is found in the local storage, when the strategy used is localStorage

Or at least there should be a $get(strategey) method doing something similar.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.