hashbang之后的角度替换url
Angular replace url after hashbang
在我们的应用程序中,我们提供foobar.com/public/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返回未处理(未缩小、未放大等)的文件版本。我们也在使用角度路线来表达我们的观点。
TLDR:
- 我们有一条生产路线:
foobar.com
- 我们有一个开发路线:
foobar.com/debug
- 我们有一个基本标签:
<base href="http://foobar.com/public/whatever">
- 我们使用hashbang-urls进行角度路由
问题是在客户端生成url。正如评论中所讨论的,<a href="#/new/route">Click here</a>
不起作用,因为生成的url包含基本标记,服务器拒绝该基本标记,并且由于用户从其他地方开始,所以看起来很奇怪:foobar.com/public/angular/#/myRoute
)。我能想到的最好的创建所需url的方法是:
/**
* 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?
您是否考虑过使用UI路由器库?
总的来说,它非常棒。
针对您的问题,UrlMatcher服务提供了一种方法format
,除非我误解了您的要求,否则它会做您想做的事情。
new UrlMatcher('/your/route/here').format(optionalNamedParameters);
// returns a formatted URL
- 替换url中变量的值
- hashbang之后的角度替换url
- 为出版商学术界登录替换url中的域
- 重定向javascript,替换url
- javascript替换url链接循环
- 如何替换URL的一段并重新加载页面
- 单击时尝试替换URL中的值
- 替换 URL 字符串中的撇号时出现问题
- 在 javascript 中替换 URL 中的两个元素
- 使用 jQuery 替换 URL 中的值
- 为什么添加而不是替换 URL 哈希
- 使用 regEx 替换 url 之间的值
- JQuery 根据 HTML 下拉列表选择查找并替换 URL 中的查询字符串
- 替换URL'中的字符串查询;s与Javascript(有条件)
- 替换URL字符串中的括号
- Regex-用图像标记替换URL
- 用Javascript Regex替换url中的子目录
- JavaScript字符串替换URL参数
- 使用正则表达式替换url中的字符串
- 如何替换URL字符串中的字符