在我们的应用程序中,我们提供 foobar.com/public/angular
中的静态 Angular 应用程序文件。 。主页 ( foobar.com
) 配置为服务 foobar.com/public/angular/index.html
。因此,在我们的索引文件的<head>
中,我们有:
<base href="http://foobar.com/public/angular">
但是,在开发过程中,我们使用 foobar.com/debug
,这会导致服务器使用它:
<base href="http://foobar.com/public/angular-debug">
服务器从该 url 返回文件的未处理(未缩小、丑化等)版本。我们还在 View 中使用 Angular-route。
TLDR:
- 我们有一条生产路线:
foobar.com
- 我们有一条开发路线:
foobar.com/debug
- 我们有一个基本标签:
<base href="http://foobar.com/public/whatever">
- 我们正在使用 hash-bang url 进行 Angular 路由
问题是在客户端生成 url。正如评论中所讨论的,<a href="#/new/route">Click here</a>
不起作用,因为生成的 url 包含基本标记,服务器拒绝该标记并且看起来很奇怪,因为用户从其他地方开始:foobar.com/public/angular/#/myRoute
)。我能想到的创建所需网址的最佳方法是:
/**
* Returns current url after replacing everything after the hashbang with a new string.
*
* @param {string} s - string to change route with (e.g. 'asdf')
* @return {string} - new url e.g. http://google.com/foobar/#!/asdf
*/
makeRouteUrl = function(s) {
var root = $location.absUrl().match(/.*#!/);
if (root && (root.length > 0)) {
root = root[0];
return( root + s );
} else {
// no hashbang in path? Choose home page (not intended use)
return "/";
}
}
但是,这看起来有点恶心。 Angular 中是否有一个函数可以使上述函数变得不必要?我在 $location、$route 等中寻找过函数,但似乎没有任何东西可以正确处理我们复杂的设置。我们最终需要以字符串形式获取 url,而不是导航(我们支持在新选项卡中打开,因此需要使用 ng-href
)。由于 Angular 应用程序经常使用 hashbang url 进行路由,因此我认为一定有某种东西可以让您在 hashbang 之后更改路由,同时仍然保留其前面的内容。
最佳答案
我不完全确定我是否理解这个问题......
$location.url('/stuff/after/hash?params=hey');
或者如果你只想设置#后面的路径:
$location.path('/stuff/after/hash');
这是我经常使用的。但是在此之后您需要返回没有哈希值的 url 吗? 怎么样
window.location.origin + window.location.pathname
对于没有哈希值和参数的当前 url?
关于javascript - Angular 在 hashbang 之后替换 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28708097/