Tuesday 24 November 2015

session tracking in angularjs using custom service value provider recipe







HTTP is a stateless protocol. Each time a client retrieves a new information, it opens a seperate connection to the web / application server. The server does not automatically maintains the contextual information of the client. It leads to many difficulties. Typical example being the online store. User adds the products on the cart by visiting various views. 



There are various solutions available to maintain the session.
e.g. using the cookies, URL re-writting and using the hidden fields.



In online store application created using angular we can also maintain the state of the cart across the various views and controllers.

How we can do it in angular?

Angular provides a way to create services using various recipes which can hold the data.


Step 1. Create a service using value recipe. 
Step 2. Create a cart object inside this service.
Step 3. Provide the cart manipulation operations like update, delete, add Cart to this service.
step 4: Inject this service to the controllers in the online store application.
step 5. Angular makes the service available to all the controllers wherever this cart Service is injected. 

When the angular application bootstraps, it creates service which holds the empty cart object. 

All objects in angular being singleton the same object is made available to all the controllers thereby maintaining the state of the cart across the views.



Online store example

In typical shopping cart we buy products on various product / category pages and keep updating the cart. Here are the steps.

Step 1:  Create the angular application file say main.js

var app = angular.module('shopingCart', ['ngRoute']);

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/page1', {
      tempateUrl: 'page1.html',
      controller: 'page1cntrl'
    })
    .when('/page2', {
      templateUrl: 'page2.html',
      controller: 'page2cntrl',
    })
    .when('/showCart', {
      templateUrl: 'cart.html',
      controller: 'cartcntrl',
    })   

    .otherwise({ // default action of route
      redirectedTo: '/page1'
    })
}]);
Step 2: Create the index.html file


    Shopping Cart
 
  
 
Step 3 :  Create a js file called session-service.js

Here we create the custom injectable service having a cart inside using the "value provider recipe". 

'use strict';
function Cart() {
  return {
    'cartId': '',
    'cartItem': []
  };
}
// custom service maintains the cart along with its behavior to clear itself , create new , delete Item or update cart

app.value('sessionService', {
  cart: new Cart(),
  clear: function() {
    this.cart = new Cart();
    // mechanism to create the cart id 
    this.cart.cartId = 1;
  },
  save: function(session) {
    this.cart = session.cart;
  },
  updateCart: function(productId, productQty) {
    this.cart.cartItem.push({
      'productId': productId,
      'productQty': productQty
    });
  },
//delete Item and other cart operations function goes here...
});

Product page 1 and its controller
page1.html

Product 1 Page

Added to Cart

page1cntrl.js

'use strict';
angular.module('shopingCart').controller('page1cntrl',['$scope','sessionService',function($scope,sessionService){
// in this controller the sessionService has been injected as dependency
// retrieve the session information from the service to the scope using the following stt.
    $scope.sessionData  = sessionService;
    $scope.updateCart = function(id,qty) {
    $scope.itemBought = true;
    sessionService.updateCart(id,qty); // call the service method to update the cart.
  };
}]);

page2.html

Product 2 Page

Added to Cart

page2cntrl.js
'use strict';
angular.module('shopingCart').controller('page1cntrl',['$scope','sessionService',function($scope,sessionService){
// in this controller the sessionService has been injected as dependency
// retrieve the session information from the service to the scope using the following stt.
    $scope.sessionData  = sessionService;
 // for demo and understanding purpose we have duplicated the same method in the two controllers.
// how ever we can create the commonMethods which can be accessed from various different controllers.
I will soon be posting how to create the common methods which can be accessed by different controllers.

  $scope.updateCart = function(id,qty) {
   $scope.itemBought = true;
   sessionService.updateCart(id,qty); // call the service method to update the cart.
  };

}]);
cart.html

Cart

Product idproduct Qty
{{cartItem.id}} {{cartItem.qty}}
Cart is Empty
cartcntrl.js
'use strict';
  angular.module('shopingCart').controller("cartcntrl",
            ['$scope','sessionService',
                       function($scope,sessionService) {
                                  $scope.sessionData = sessionService;
                                   $scope.varShowCart = true;
                                   sessionService.save($scope.sessionData);
          }]);


Note:

This session object needs to be stored in local storage like "$window.sessionStorage" , session object or any other mechanism. The current object will be lost once the user refreshes the page.
 

Further reading

There are different recipes (methods) using which we can create custom angular service these are
1. Service
2. Factory
3. Value
4. Constant and
5. $provide

The first  4 are the specialized version of the $provide. For more details you can refer https://docs.angularjs.org/api/auto/service/$provide



65 comments:

  1. Typically session should refers to till user is on the same page, it should persist the data. but the way you have built the session service. It flush outs a data when page gets refreshed per angular life cycle(This is not how session works). Ideally service should internally deals with localstorage/Session object for data storage.

    ReplyDelete
    Replies
    1. Hi Pankaj,

      Thanks for your feedback. Certainly it is required to store it as you mentioned.

      I will include this part soon nevertheless this tutorial focus only on how we can maintain the the state across the pages and controllers.

      Delete
  2. Hi, I am doing something similar to this in a project I am creating. I am integrating an application that uses php to allow users to login. My job is to create the shopping cart which I have done and I can save the data to local storage. This is no good to me though as i need to save the data in someones cart to a particular person who is logged in. The current system I have allows users to log in and add items to a cart but if i login with a new person, the items are still stored from the previous person.

    I hope you can help my friend.

    ReplyDelete
  3. I really enjoy the blog.Much thanks again. Really Great.

    Offshore Angularjs Developers

    ReplyDelete
  4. I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in ANGULAR JS, kindly contact us http://www.maxmunus.com/contact
    MaxMunus Offer World Class Virtual Instructor led training on ANGULAR JS. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
    For Demo Contact us.
    Nitesh Kumar
    MaxMunus
    E-mail: nitesh@maxmunus.com
    Skype id: nitesh_maxmunus
    Ph:(+91) 8553912023
    http://www.maxmunus.com/




    ReplyDelete


  5. Hai Author Good Information that i found here,do not stop sharing and Please

    keep updating us..... Thanks

    ReplyDelete
  6. Great efforts put it to find the list of articles. thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.
    Angular JS Training in Chennai | Angular JS Training in Velachery

    ReplyDelete
  7. This is an best post. It is Really very informative concept.I like it and help me to development very well.Thanks alot for this brief explanation and very nice information.Angular Js Course HYDERABAD

    ReplyDelete
  8. Hey are you instested to learn aws training in hyderabad ? Get certified if you have interest.

    ReplyDelete
  9. Thank you for providing such an awesome article and it is a very useful blog for others to read.

    Oracle ICS Online Training

    ReplyDelete
  10. Rất vui và hạnh phúc khi đọc được bài viết của bạn. Cảm ơn bạn đã chia sẻ.

    Lều xông hơi khô

    Túi xông hơi cá nhân

    Lều xông hơi hồng ngoại

    Mua lều xông hơi

    ReplyDelete
  11. It is an impressive article. It is very useful. Thank you for sharing this with us.

    Angular JS Online training
    Angular JS Training in Hyderabad

    ReplyDelete
  12. This is an best post. It is Really very informative concept.I like it and help me to development very well.Thanks alot for this brief explanation and very nice information. I had found the best institute for angular training
    online with 8+ years experienced faculty and free bundle videos.

    Contact No:- 9885022027
    Whatsapp also available.

    ReplyDelete
  13. nice Post
    We are the best piping design course in Hyderabad, India. Sanjary academy Offers Piping Design Course and Best Piping Design Training Institute in Hyderabad. Piping Design Institute in India Piping Design Engineering.
    Piping Design Course
    Piping Design Course in india
    Piping Design Course in hyderabad

    ReplyDelete
  14. Thanks for sharing information
    Sanjary kids is the best playschool, preschool in Hyderabad, India. Start your play school,preschool in Hyderabad with sanjary kids. Sanjary kids provides programs like Play group,Nursery,Junior KG,Serior KG,and Teacher Training Program.
    play school in hyderabad
    Preschool in hyderabad
    Preschool teacher training course in hyderabad
    pre and primary teacher training course in hyderabad

    ReplyDelete
  15. We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming (7+ years) will ensure that we will deliver our best in python training in vijayawada. , and we believe that no one matches us in this context.

    ReplyDelete
  16. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    microservices online training
    top microservices online training
    best microservices online training

    ReplyDelete
  17. Nice Post. I got more information from your blog it's very helpful. Hope it might be very useful for many people as well. keep on updating...!!


    Artificial Intelligence Training in Hyderabad

    ReplyDelete
  18. Top Chauffeur service in Melbourne
    Whether you need a last minute chauffeur car or a planned vehicle for your outing, book with us and get served on time. With well-mannered chauffeurs and finest vehicles, we arrange to pick and drop our customers with great punctuality. A hassle-free traveling experience waits at Silver Executive Cab for every customer

    ReplyDelete
  19. Best Immigration Lawyer in Brampton
    Best Real Estate Lawyer in Toronto
    We specialize in assisting clients in the areas of Real Estate, Corporate and Commercial, Wills and Estates, Immigration and more.
    BTorres Law Office offers an innovative and results-oriented approach to building solid working relationships with all of our valued clients.
    Our shared values, and our commitment to the highest standards of the practice of law is our top priority.

    ReplyDelete
  20. Thanks for your Guidance...The Concept of the Topics and way of Explanation's is very Good...Your Effective Works clear all My Queries...Good Job
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  21. This is really impressive post, I am inspired with your post, do post more blogs like this, I am waiting for your blogs.
    Full Stack Online Training

    ReplyDelete

  22. The Way Of Explaination Is Very Good And Nice Informative Topic You Have Choosen..
    AWS Course in Hyderabad

    ReplyDelete
  23. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
    machine learning courses in bangalore

    ReplyDelete
  24. Nice blog. Thank you for sharing. The information you shared is very effective for learners I have got some important suggestions from it.
    Best software development company in Toronto

    ReplyDelete

  25. Blog commenting : Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    devops online training
    best angularjs online training
    top angularjs online training

    ReplyDelete
  26. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    AngularJS online training
    best AngularJS online training
    top AngularJS online training

    ReplyDelete
  27. Thank you for sharing this useful article with us. This blog is a very helpful to me in future. Keep sharing informative articles with us.

    https://www.ahmedabadcomputereducation.com/course/php-training-course/

    ReplyDelete
  28. Thank you for sharing this useful article. This blog is a very helpful to me. Keep sharing informative articles with us.

    https://www.france-collectivites.fr/

    ReplyDelete
  29. Thank you for sharing this useful article with us. This blog is a very helpful to me. Keep sharing informative articles with us.

    https://www.sdsfin.in/services/project-finance-consultants-in-ahmedabad/

    ReplyDelete
  30. The following time I read a blog, I trust that it doesn't bomb me similarly as much as this specific one. That is to say, I realize it was my decision to peruse, regardless I really trusted you would presumably have something valuable to discuss. All I hear is a lot of crying about something you could fix on the off chance that you were not very bustling searching for consideration.
    evrmag

    ReplyDelete
  31. It's a very informative blog and I am exactly looking for this type of blog. Thank you for sharing this beautiful blog.

    https://superurecoat.com/titanium-iso-propoxide/

    ReplyDelete
  32. Thank You for sharing this informative article.

    https://web30india.com/

    ReplyDelete
  33. I visited various websites but the audio feature for audio songs current at this site is really wonderful.|
    data scientist training and placement in hyderabad

    ReplyDelete
  34. Well-written and informative blog. I really liked it. I appreciated your effort in this blog. Keep sharing more!
    Data Science Course in Hyderabad

    ReplyDelete
  35. Stupendous blog huge applause to the blogger and hoping you to come up with such an extraordinary content in future. Surely, this post will inspire many aspirants who are very keen in gaining the knowledge. Expecting many more contents with lot more curiosity further.

    data science course in bangalore with placement

    ReplyDelete
  36. Thanks for the session on Angular js , it is really very helpful. Keep sharing

    Data Science Training in Pune

    ReplyDelete


  37. Wow. That is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious.I want to refer about the best
    sap abap training in bangalore . They Provide 100% Placement Program .

    ReplyDelete
  38. Here is the best music to calm and relax your mind

    1. best relaxing music
    2. best Depp sleep music
    3. best meditation music
    4. best calm music
    5. best deep focus music

    ReplyDelete
  39. Very Nice Blog…Thanks for sharing this information with us. Here am sharing some information about training institute.
    data management services by neurogaint

    ReplyDelete
  40. This is really an awesome article. Thank you for sharing this.It is worth reading for everyone.
    Offshore Angularjs Development Company – Nintriva

    ReplyDelete

  41. This post will be very useful to us....i like your blog and helpful to me...
    Outsource Angular Development in India

    ReplyDelete
  42. Nice blog. Informative and knowledgeable content. Big thumbs up for this blog. I really enjoyed this blog. Thank you for sharing with us.
    Data Science Institute in Hyderabad
    Data Science Course Training Institute in Hyderabad

    ReplyDelete
  43. Thanks for letting me know about Best CA Academy in Hyderabad
    Best CA Academy in Hyderabad

    ReplyDelete
  44. I appreciate you sharing the best knowledge, and this blog is crucial.
    Top CEC colleges in Hyderabad

    ReplyDelete