【问题标题】:Refreshing the browser bypasses angular on routerProvider based URLs刷新浏览器绕过基于 routerProvider 的 URL 的 Angular
【发布时间】:2013-07-27 16:52:31
【问题描述】:

我有一个支持 angularjs 前端的 grails 应用程序。它们被部署为单个 WAR。我已经从应用程序中删除了上下文路径,以便它在 http://localhost:8080 上运行。

我有一个文章列表,我有$routeProvider 设置将/ 重定向到/articles,此时控制器接管并通过$http 提取列表。很标准的东西。

最初,我使用默认位置提供程序配置,因为在 URL 中使用了哈希 (#)。我已经通过

$locationProvider.html5Mode(true);

一切仍然有效。但是,如果我直接在地址栏中更改 URL 并按 Enter 键,或者如果我只是在 /articles 处刷新浏览器,则服务器端会接管并且我只是将我的文章列表作为 json 获取。没有棱角。我理解为什么会发生这种情况,现在我所做的是在服务器上检测到一个非 ajax 请求并发出重定向到/,这将允许 angular 启动。

我想知道这是否正确。或者还有什么我可以做的更好的做法。

【问题讨论】:

  • #s 不能使用标准方式是有原因的吗?
  • 并非如此。我只是想学习 angularjs,并尝试不同的方法来看看什么最适合我想要实现的目标。

标签: grails angularjs


【解决方案1】:

重定向是正确的解决方案。

我能够使用 url 映射使其工作。到目前为止它有效:-)

我是这样开始的:

"/**" (controller: 'app', action: 'index') 

app/index 是 Angular 应用页面。但这也将匹配其他所有内容(例如 /$controller/$action)。我必须将每个 $controller/$action 显式映射到正确的控制器。不太好... ;-)

为了解决这个问题,我在所有 uris 前面加上 /client 用于角度路由,/server 用于 grails uris。这使得 url 映射变得容易,它有助于区分角度路由和模板 uris 等。

我的最终 url 映射如下所示:

class UrlMappings {
    static excludes = [
        "/lib/**",
        "/css/**",
        "/js/**"
    ]

    static mappings = {
        // - all client uris (routes) will start with '/client/',
        // - all server uris (load)   will start with '/server/'

        // redirect /$appName/ to /$appName/client
        "/" (controller: 'redirect', action: 'redirectTo') {
            to = '/client/'
            permanent = true
        }

        // redirect any angular route       
        "/client/**" (controller: 'app', action: 'index')


        // standard controller/action mapping
        "/server/$controller/$action/$id?"  {
            constraints {
            }
        }
    }
}

在url映射中不能直接重定向,所以我用一个简单的控制器:

class RedirectController {
    def redirectTo () {
        redirect (uri: params.to, permanent: params.permanent)
    }
}

路由条目如下所示:

$routeProvider.when ('/client/login', {templateUrl: './server/security/login'});

【讨论】:

    【解决方案2】:

    刚刚在这里回答了这个问题 angularjs html5mode refresh page get 404

    确保您重写规则在服务器上正常工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-08
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      相关资源
      最近更新 更多