简体   繁体   中英

Angular JS - Route to Non Single Page SPA

We need to load some pages in non SPA mode, while others in SPA mode. For example, homepage and about pages should be non SPA, while other pages should be SPA.

$locationProvider.html5Mode(true); makes all pages SPA, even though route is not found. Not adding that line makes all pages non SPA.

How do I set up routing so that if a route is not present the page should be fetched from the server? ie not be pushstate.

Also, we're using ui-router.

Using ui-router, you can have an otherwise state. In that otherwise state, you can add a resolve that can do a request to the server to handle the routing :

$urlRouterProvider.otherwise("otherwise");

$stateProvider
  .state('otherwise', {
    url: '/otherwise',
    template: 'some html',
    resolve : {
      serverPage: function servePage() {
        //http request to the server to fetch and redirect. 
      }
    }
  })

not sure why the earlier answer with an 'otherwise' state did not work, since that seemed promising. if you have multiple non-spa pages to go to, and you want to manage all of that in routes, you can also just pass in a function to otherwise(), rather than define a separate state, like so:

$urlRouterProvider.otherwise(function($injector, $location){
    // redirect here, for example…
    window.location.href= window.location.origin + $location.url();
});

So that if the user navigates to the following route

http://mydomain.com/spa#/nonspa

It would be redirected to

http://mydomain.com/nonspa

(assuming 'nonspa' in not a valid route)

That said, I might just do a direct link to the non-spa page instead of going through the routing code -- seems simpler and faster.

将target =“_ self”属性添加到锚标记是否允许您从SPA页面转到非SPA页面?

OK, so I tweaked the previous answers and found a workaround

Basically, when the server is called for an SPA or non SPA page, the page needs to somehow indicate what mode it is running in. I choose a javascript variable for that

var html5mode = true;// for SPA, set to false for non SPA. Emit this from the server.

In your routedefs.js or where ever you have the routes defined.

// enable html5Mode for pushstate ('#'-less URLs)
if (html5mode) {
     $urlRouterProvider.otherwise(function ($injector, $location) {
         // reload if route not found.
         window.location = window.location;
     });

     $locationProvider.html5Mode(true);
} else {
     $locationProvider.html5Mode(false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM