Page refresh using AngularJS service and views

I have a simple SPA with two views: list view and detailed view. I am using a service called StateService to transfer data between two controllers.

I am trying to handle the case when the user refreshes the browser page - when this happens, the StateService gets reinitialized and the detailed view no longer works. I want to determine when this will happen and return the user to the list.

Here is a simplified version of my public service. The idea is that I would set isInitialized to true when I switch to the detailed view so that I can detect when the service was not properly initialized.

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

This is what I tried in the first lines of my controller. StateService is successfully implemented in 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 make this code work, or better ideas on what to do when the 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 hits. 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 be working as expected.

+4
source share
1 answer

I think you have trouble viewing. variables in javascript have a scope function. isInitialized refers only to your StateService function, so you cannot get it outside of your StateService function.

not sure exactly how you get this thing in your controller, but maybe this will help:

if you use angular module.service () to use StateService as a constructor to inject (the new StateService) into your controller, then you need to set isInitialized in the instance

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

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

If you just use module.factory () or something else that doesn't use the new ones, then you need to put your isInitialized value somewhere else, which you really can get.

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

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1493191/


All Articles