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 id | product Qty |
---|---|
{{cartItem.id}} | {{cartItem.qty}} |
Cart is Empty
'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
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.
ReplyDeleteHi Pankaj,
DeleteThanks 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.
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.
ReplyDeleteI hope you can help my friend.
I really enjoy the blog.Much thanks again. Really Great.
ReplyDeleteOffshore Angularjs Developers
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
ReplyDeleteMaxMunus 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/
ReplyDeleteHai Author Good Information that i found here,do not stop sharing and Please
keep updating us..... Thanks
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.
ReplyDeleteAngular JS Training in Chennai | Angular JS Training in Velachery
ReplyDeleteyours blog was excellent and really enjoyed.Thanks for sharing and mainting blogging
Data science online training in Hyderabad
Data science training in usa
Data science training in uk
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
ReplyDeletevery interesting to read…
ReplyDeleteCEH Training In Hyderbad
Fabulous post admin, it was too good and helpful. Waiting for more updates.
ReplyDeleteRPA Training in Chennai
Blue Prism Training in Chennai
UiPath Training in Chennai
AWS Training in Chennai
DevOps Training in Chennai
Data Science Course in Chennai
ccna course in Chennai
Hey are you instested to learn aws training in hyderabad ? Get certified if you have interest.
ReplyDeleteThank you for providing such an awesome article and it is a very useful blog for others to read.
ReplyDeleteOracle ICS Online Training
I feel happy to see your webpage and looking forward for more updates.
ReplyDeleteR Programming Training in Chennai
Data Analytics Training in Chennai
Machine Learning Course in Chennai
Machine Learning Training in Velachery
Data Science Course in Chennai
Data Analytics Courses in Chennai
Data Analyst Course in Chennai
Machine Learning course in Chennai
ReplyDeletenice course. thanks for sharing this post.
AngularJS Training in Noida
This is really great informative blog. Keep sharing.....
ReplyDeleteGCP Training
Google Cloud Platform Training
GCP Online Training
Google Cloud Platform Training In Hyderabad
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ẻ.
ReplyDeleteLề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
This content is really helpful for me and I learn more details with a deep explanation about this topic. Thank you...!
ReplyDeleteExcel Training in Chennai
Advanced Excel Training in Chennai
Unix Training in Chennai
Oracle Training in Chennai
Tableau Training in Chennai
Linux Training in Chennai
Social Media Marketing Courses in Chennai
Power BI Training in Chennai
Excel Training in Porur
Excel Training in OMR
Thanks, Good post..Keep on sharing....
ReplyDeleteGCP Training
Google Cloud Platform Training
GCP Online Training
Google Cloud Platform Training In Hyderabad
It is an impressive article. It is very useful. Thank you for sharing this with us.
ReplyDeleteAngular JS Online training
Angular JS Training in Hyderabad
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
ReplyDeleteonline with 8+ years experienced faculty and free bundle videos.
Contact No:- 9885022027
Whatsapp also available.
nice Post
ReplyDeleteWe 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
Thanks for sharing information
ReplyDeleteSanjary 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
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.
ReplyDeleteThanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
ReplyDeletemicroservices online training
top microservices online training
best microservices online training
Find my blog post here
ReplyDeletehttp://ttlink.com/bookmark/d3913482-056d-4e38-82e1-baa1036528ba
http://ttlink.com/bookmark/5931d44a-7910-41ec-9bab-f2b3082de030
http://ttlink.com/bookmark/3f596fd1-f173-4b25-ba95-0730a97ab3a8
Best Web Development Tools for Web Developers.
I really enjoyed to read this blog...i got lot of useful information from this blog…
ReplyDeleteAWS Training in Chennai
AWS Training in Bangalore
AWS Training in BTM
AWS Training in Marathahalli
Best AWS Training in Marathahalli
PHP Training in Bangalore
Spoken English Classes in Bangalore
Best AWS Training in Bangalore
Data Science Courses in Bangalore
DevOps Training in Bangalore
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...!!
ReplyDeleteArtificial Intelligence Training in Hyderabad
Top Chauffeur service in Melbourne
ReplyDeleteWhether 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
Best Immigration Lawyer in Brampton
ReplyDeleteBest 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.
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
ReplyDeleteJava training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery
ReplyDeleteThe post educates and inspires me a lot. This topic is excellent and this would provide tremendous solution for its readers. Web Designing Course Training in Chennai | Web Designing Course Training in annanagar | Web Designing Course Training in omr | Web Designing Course Training in porur | Web Designing Course Training in tambaram | Web Designing Course Training in velachery
thanks for sharing nice information....
ReplyDeleteAWS Training in Hyderabad
This is really impressive post, I am inspired with your post, do post more blogs like this, I am waiting for your blogs.
ReplyDeleteFull Stack Online Training
ReplyDeleteThe Way Of Explaination Is Very Good And Nice Informative Topic You Have Choosen..
AWS Course in Hyderabad
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.
ReplyDeletemachine learning courses in bangalore
nice to learn new things good.
ReplyDeleteRobotic Process Automation (RPA) Training in Chennai | Robotic Process Automation (RPA) Training in anna nagar | Robotic Process Automation (RPA) Training in omr | Robotic Process Automation (RPA) Training in porur | Robotic Process Automation (RPA) Training in tambaram | Robotic Process Automation (RPA) Training in velachery
Nice blog. Thank you for sharing. The information you shared is very effective for learners I have got some important suggestions from it.
ReplyDeleteBest software development company in Toronto
ReplyDeleteBlog 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
Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
ReplyDeleteAngularJS online training
best AngularJS online training
top AngularJS online training
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.
ReplyDeletehttps://www.ahmedabadcomputereducation.com/course/php-training-course/
Thank you for sharing this useful article. This blog is a very helpful to me. Keep sharing informative articles with us.
ReplyDeletehttps://www.france-collectivites.fr/
Thank you for sharing this useful article with us. This blog is a very helpful to me. Keep sharing informative articles with us.
ReplyDeletehttps://www.sdsfin.in/services/project-finance-consultants-in-ahmedabad/
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.
ReplyDeleteevrmag
It's a very informative blog and I am exactly looking for this type of blog. Thank you for sharing this beautiful blog.
ReplyDeletehttps://superurecoat.com/titanium-iso-propoxide/
Thank you for sharing valuable information with us. Exactly, I am looking for this types of blog.
ReplyDeleteLoan Against Property
Loan Against Property in Vadodara
Loan Against Property in Ahmedabad
Loan Against Property Companies
Loan Against Property Interest Rate
ReplyDeleteI really want to appreciate the way to write this
omni-channel
ivrs
ip-pbx
Call Center Software
Call Center Solution
Call Center Solutions
Thank You for sharing this informative article.
ReplyDeletehttps://web30india.com/
I visited various websites but the audio feature for audio songs current at this site is really wonderful.|
ReplyDeletedata scientist training and placement in hyderabad
Well-written and informative blog. I really liked it. I appreciated your effort in this blog. Keep sharing more!
ReplyDeleteData Science Course in Hyderabad
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.
ReplyDeletedata science course in bangalore with placement
Excellent Blog. Thank You for Sharing!
ReplyDeleteBest Mobile App Development Company in UK | Mobile App Development Services
Thanks for the session on Angular js , it is really very helpful. Keep sharing
ReplyDeleteData Science Training in Pune
thanks for sharing this post with us
ReplyDeletefull stack developer course
full stack developer course in bangalore
ReplyDeleteWow. 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 .
Here is the best music to calm and relax your mind
ReplyDelete1. best relaxing music
2. best Depp sleep music
3. best meditation music
4. best calm music
5. best deep focus music
Very Nice Blog…Thanks for sharing this information with us. Here am sharing some information about training institute.
ReplyDeletedata management services by neurogaint
This is really an awesome article. Thank you for sharing this.It is worth reading for everyone.
ReplyDeleteOffshore Angularjs Development Company – Nintriva
thanks for sharing such an useful info..
ReplyDeleteSignova Group
ReplyDeleteThis post will be very useful to us....i like your blog and helpful to me...
Outsource Angular Development in India
Nice blog. Informative and knowledgeable content. Big thumbs up for this blog. I really enjoyed this blog. Thank you for sharing with us.
ReplyDeleteData Science Institute in Hyderabad
Data Science Course Training Institute in Hyderabad
Android Mobile App Development in Ahmedabad
ReplyDeleteWeb 3.0 India is the most trusted Web3 Blockchain Development and NFT Development Company in USA. We also provides ICO, STO development for cryptocurrency.
https://web30india.com/
Thanks for letting me know about Best CA Academy in Hyderabad
ReplyDeleteBest CA Academy in Hyderabad
I appreciate you sharing the best knowledge, and this blog is crucial.
ReplyDeleteTop CEC colleges in Hyderabad