Phil Sandler
Phil Sandler

Reputation: 28016

Handling Page Refresh with AngularJS Service and Views

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.

Upvotes: 4

Views: 6471

Answers (1)

fess .
fess .

Reputation: 1549

I think you have a problem with scoping. variables in javascript have function scope. isInitialized is scoped only to your StateService Function, so you can't get at it outside of your StateService Function.

not sure exactly how you're getting this thing into your controller, but maybe these help:

if you're using an angular's module.service() to use StateService as a constructor to inject a (new StateService) into your controller then you need to set isInitialized on the instance

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

This way (new StateService).isInitialized === false

If you are just using module.factory() or something else that doesn't use new, then you need to put your isInitialized value somewhere else you can actually get at it.

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

Hope that helps.

Upvotes: 1

Related Questions