Handling Page Refresh with AngularJS Service and Views

5,596 views
Skip to first unread message

Phil Sandler

unread,
Jul 24, 2013, 11:00:50 AM7/24/13
to ang...@googlegroups.com
I posted this on StackOverflow as well.  Feel free to answer there if you want rep.  :)


I can post additional code about how I create my services, etc. if necessary.  

----------------------------------------------------------------------------

I have a simple SPA with two views: a list view and a detail view. I use a service called StateService to pass data between the two controllers.

I am trying to handle the case where the user refreshes the browser page--when this happens, the StateService gets reinitialized and the detail view can no longer work. I want to detect when this happens and return the user to the list view.

Here is a simplified version of my State Service. The idea is that I would set isInitialized to true when I switch to the detail view so that I can detect when the service has not been properly initialized.

var StateService = function () {
    var isInitialized = false;
};

This is what I have tried in the first few lines of my controller. The StateService is being successfully injected into the controller.

//always returns [Object], on refresh or navigating from list page
alert(StateService); 
// this next line always returns undefined.  Should be false since I am initializing
// the value to false?
alert(StateService.isInitialized); 
//One of the many combinations I have tried . . .
if (!StateService.isInitialized | StateService.isInitialized == false) {
    $location.path('/');
}

I don't know if this is a gap in my understanding of javascript or angular, but any thoughts on how I can get the above code to work, or better ideas on what to do when a user refreshes the page?

Edit

Using console.log as recommended by nycynik I see the following:

c {} [StateService]
undefined [StateService.isInitialized]

So it seems that StateService itself is just an empty object when this code gets hit. I get the same results from my other controller (the one that handles the list view).

As noted in the comments, the service seems to otherwise work as expected.

Alexander Kohout

unread,
Jul 25, 2013, 2:53:08 AM7/25/13
to ang...@googlegroups.com
You must somehow store your state, so that you can access the data after page refreshes. If the user refreshes the page, it loads all JS files and therewith you can't take over the data in your service.

What if you always keep your current state in cookie/localStorage/sessionStorage? When loading the page, you load the last state from your stored state. 
Reply all
Reply to author
Forward
0 new messages