Rails + Angular:登录/注册后重定向

Mor*_*gan 5 redirect ruby-on-rails angularjs url-redirection

我正在使用Rails + Devise进行登录和注册,但我的前端绝大多数都使用角度路由.当有人试图在没有登录的情况下转到特定页面时,我希望在成功登录后重定向它们.通常,这将是在会话中存储路径和修改after_sign_in_path_for方法的简单问题.但是,我似乎无法找到有效获取实际路径的Rails方法.我有信心我可以通过JS做到这一点,然后将其存储为cookie(或者真的是Angular),但我更喜欢将它保存在Rails中.有没有一种我想念的方法会给我一些实际的路径,包括/#/ what/whatever?

似乎以下应该有效:

  request.original_url
Run Code Online (Sandbox Code Playgroud)

基于此(http://api.rubyonrails.org/classes/ActionDispatch/Request.html)

但它没有返回主题标签或以下参数.

也许是由于这个人说的话(没有哈希'#'的AngularJS路由)

#是一个旧的浏览器短路,它不会触发请求,这允许许多js框架在其上构建自己的客户端重新路由.

有没有一种干净的方法来收集Rails中的完整路径,还是我需要进入Angular/JS?

Bra*_*ary 4

我也遇到了同样的问题,但是是用 Backbone 的。问题是浏览器不会将URL的锚点部分发送到服务器,因此Rails无法处理这个问题,只能由前端的JS处理。

我正在发布对我有用的解决方法。

在登录页面中添加此 javascript 代码段(最有可能在 app/views/sessions/new.html.haml 中)

:javascript
  // keeping the hash route into a cookie to retrieve it after sign in redirect
  cname = 'hash_route'
  cvalue = window.location.hash
  // checking if the hash value is blank, don't overwrite the cookie
  // this check covers the case of user giving wrong credentials in login
  // then successfully login within the expiration time of the cookie
  // other cases that aren't supported are relatively rare
  if(cvalue.length){ 
    var d = new Date();
    d.setTime(d.getTime() + (3*60*1000)); // enough time to log in
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
  }
Run Code Online (Sandbox Code Playgroud)

在 SessionsController#create 中(或者您可以覆盖 Devise 方法“after_sign_in_path_for”)

def create
  # ------- Devise code --------
  self.resource = warden.authenticate(auth_options)
  set_flash_message(:notice, :signed_in) if is_navigational_format?
  sign_in(resource_name, resource)

  # ------- This is the code --------
  # handling the case of redirecting to a link that had a hash route    
  location = after_sign_in_path_for(resource)  

  if cookies[:hash_route].present?
     location+= cookies[:hash_route]
     cookies.delete :hash_route
  end

  respond_with resource, :location => location
end
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。