繁体   English   中英

Angular JS - 非单页SPA的路径

[英]Angular JS - Route to Non Single Page SPA

我们需要在非SPA模式下加载一些页面,而在SPA模式下加载其他页面。 例如,主页和关于页面应该是非SPA,而其他页面应该是SPA。

$ locationProvider.html5Mode(真); 即使找不到路由,也会使所有页面都SPA。 不添加该行会使所有页面都不是SPA。

如何设置路由,以便在路由不存在时,应从服务器获取页面? 即不是pushstate。

另外,我们正在使用ui-router。

使用ui-router,您可以拥有其他状态。 在其他状态下,您可以添加可以向服务器请求处理路由的解析:

$urlRouterProvider.otherwise("otherwise");

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

不确定为什么早期以“其他”状态回答的问题不起作用,因为这似乎很有希望。 如果您要访问多个非spa页面,并且想要在路由中管理所有这些页面,您也可以将函数传递给otherwise(),而不是定义单独的状态,如下所示:

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

因此,如果用户导航到以下路线

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

它将被重定向到

http://mydomain.com/nonspa

(假设'nonspa'不在有效路线中)

也就是说,我可能只是直接链接到非spa页面而不是通过路由代码 - 看起来更简单,更快。

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

好的,所以我调整了之前的答案并找到了解决方法

基本上,当为SPA或非SPA页面调用服务器时,页面需要以某种方式指示它正在运行的模式。我为此选择了一个javascript变量

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

在您的routedefs.js或您定义路线的地方。

// 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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