Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Best Way to Handle State on Manually Entered URLs

I currently have a set-up based on the meanjs stack boilerplate where I can have users logged in this state of being 'logged-in' stays as I navigate the URLs of the site. This is due to holding the user object in a Service which becomes globally available.

However this only works if I navigate from my base root, i.e. from '/' and by navigation only within my app.

If I manually enter a URL such as '/page1' it loses the global user object, however if I go to my root homepage and navigate to '/page1' via the site. Then it's fine, it sees the global user object in the Service object.

So I guess this happens due to the full page refresh which loses the global value where is navigating via the site does not do a refresh so you keep all your variables.

Some things to note:

  1. I have enabled HTML5Mode, using prefix of '!'.
  2. I use UI-Router
  3. I use a tag with '/'
  4. I have a re-write rule on express that after loading all my routes, I have one last route that takes all '/*' to and sends back the root index.html file, as that is where the angularjs stuff is.

I'm just wondering what people generally do here? Do they revert the standard cookies and local storage solutions? I'm fairly new to angular so I am guessing there are libraries out there for this.

I just would like to know what the recommended way to deal with this or what the majority do, just so I am aligned in the right way and angular way I suppose.

Update:

If I manually navigate to another URL on my site via the address bar, I lose my user state, however if I manually go back to my root via the address bar, my user state is seen again, so it is not simply about loosing state on window refresh. So it seems it is related to code running on root URL.

I have an express re-write that manually entered URLs (due to HTML5 Location Mode) should return the index.html first as it contains the AngularJs files and then the UI-Route takes over and routes it properly.

So I would have expected that any code on the root would have executed anyway, so it should be similar to navigating via the site or typing in the address bar. I must be missing something about Angular that has this effect.

Update 2

Right so more investigation lead me to this:

<script type="text/javascript">
    var user = {{ user | json | safe }};
</script>

Which is a server side code for index.html, I guess this is not run when refreshing the page to a new page via a manual URL.

Using the hash bang mode, it works, which is because with hash bang mode, even I type a URL in the browser, it does not cause a refresh, where as using HTML5 Mode, it does refresh. So right now the solution I can think of is using sessionStorage.

Unless there better alternatives?

Update 3:

It seems the best way to handle this when using HTML5Mode is that you just have to have a re-write on the express server and few other things.

like image 437
iQ. Avatar asked Nov 01 '22 16:11

iQ.


2 Answers

I think you have it right, but you may want to look at all the routes that your app may need and just consider some basic structure (api, user, session, partials etc). It just seems like one of those issues where it's as complicated as you want to let it become.

As far as the best practice you can follow the angular-fullstack-generator or the meanio project.

What you are doing looks closest to the mean.io mostly because they also use the ui-router, although they seem to have kept the hashbang and it looks like of more of an SEO friendly with some independant SPA page(s) capability. You can probably install it and find the code before I explained it here so -

npm install -g meanio
mean init name
cd [name] && npm install

The angular-fullstack looks like this which is a good example of a more typical routing:

// Server API Routes
app.route('/api/awesomeThings')
  .get(api.awesomeThings);

app.route('/api/users')
  .post(users.create)
  .put(users.changePassword);
app.route('/api/users/me')
  .get(users.me);
app.route('/api/users/:id')
  .get(users.show);

app.route('/api/session')
  .post(session.login)
  .delete(session.logout);

// All undefined api routes should return a 404
app.route('/api/*')
  .get(function(req, res) {
    res.send(404);
});

// All other routes to use Angular routing in app/scripts/app.js
app.route('/partials/*')
  .get(index.partials);
app.route('/*')
  .get( middleware.setUserCookie, index.index);

The partials are then found with some regex for simplicity and delivered without rendering like:

var path = require('path');

exports.partials = function(req, res) {
 var stripped = req.url.split('.')[0];
 var requestedView = path.join('./', stripped);
 res.render(requestedView, function(err, html) {
   if(err) {
     console.log("Error rendering partial '" + requestedView + "'\n", err);
     res.status(404);
     res.send(404);
   } else {
     res.send(html);
   }
 });
};

And the index is rendered:

exports.index = function(req, res) {
  res.render('index');
};
like image 140
Dylan Avatar answered Nov 11 '22 03:11

Dylan


In the end I did have quite a bit of trouble but managed to get it to work by doing few things that can be broken down in to steps, which apply to those who are using HTML5Mode.

1) After enabling HTML5Mode in Angular, set a re-write on your server so that it sends back your index.html that contains the Angular src js files. Note, this re-write should be at the end after your static files and normal server routes (e.g. after your REST API routes).

2) Make sure that angular routes are not the same as your server routes. So if you have a front-end state /user/account, then do not have a server route /user/account otherwise it will not get called, change your server-side route to something like /api/v1/server/route.

3) For all anchor tags in your front-end that are meant to trigger a direct call to the server without having to go through Angular state/route, make sure you add a 'target=_self'.

like image 21
iQ. Avatar answered Nov 11 '22 04:11

iQ.