tri*_*ris 11 routing base href angularjs
我很难理解为什么我的基础href似乎区分大小写.我有一个带有基本href的页面,并使用angularjs路由.
HTML:
<html ng-app="app">
<head>
<base href="/Foo/"/>
</head>
<body>
<div>Foo</div>
<div ng-view></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
JS:
var module = angular.module('app', []);
module.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/Home/Page1', { templateUrl = 'partials/page1' })
.otherwise({ redirectTo: '' });
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
});
Run Code Online (Sandbox Code Playgroud)
如果我导航到http://www.example.com/Foo/,那很好.但是当我导航到http://www.example.com/foo/时,我收到一个角度误差:
Error: Invalid url "http://www.example.com/foo/", missing path prefix "/Foo" !
at Error (<anonymous>)
at Object.LocationUrl.$$parse (http://www.example.com/foo/Scripts/angular.js:4983:13)
at Object.LocationUrl (http://www.example.com/foo/Scripts/angular.js:5014:8)
at $LocationProvider.$get (http://www.example.com/foo/Scripts/angular.js:5387:21)
at Object.invoke (http://www.example.com/foo/Scripts/angular.js:2809:28)
at http://www.example.com/foo/Scripts/angular.js:2647:37
at getService (http://www.example.com/foo/Scripts/angular.js:2769:39)
at Object.invoke (http://www.example.com/foo/Scripts/angular.js:2787:13)
at $CompileProvider.directive (http://www.example.com/foo/Scripts/angular.js:3613:43)
at Array.forEach (native) angular.js:5582
Run Code Online (Sandbox Code Playgroud)
如果它有所帮助/有所作为,则站点在IIS上托管并使用MVC 4.
小智 7
我正在使用UI路由器,因此无法使用为ngRoute建议的方法来解决路由区分大小写问题.https://github.com/angular-ui/ui-router/issues/197上的解决方案 适用于路由,但不适用于发布的原始问题的基本href问题.
我能够通过为$ browser添加装饰器来解决这个问题,它将basehref和url设置为小写.如果您查看导致问题的startsWith方法中导致问题的比较值的来源,您将看到它们最终来自$ browser.
最终,该解决方案解决了路由和基本href区分大小写并且不需要$ urlRouterProvider建议.因此,如果您的DOM中没有显式设置的基本href元素,则该链接中建议的$ urlRouterProvider规则将解决您的问题.否则,这将解决基本href和路由.
使用ui-router解决基本href和路由问题的完整解决方案:
$provide.decorator('$browser', [
'$delegate', function($delegate) {
var _baseHref = $delegate.baseHref,
_url = $delegate.url;
$delegate.baseHref = function() {
return angular.lowercase(_baseHref());
};
$delegate.url = function(url, replace) {
// no need to modify the setter
if (url) {
return _url(url, replace);
}
// just lowercase the getter
return angular.lowercase(_url());
};
return $delegate;
}
]);
Run Code Online (Sandbox Code Playgroud)
有同样的问题,但有不同的解决方案。这对我有用,并且不会干扰路由,beginsWith或事物应该/应该是小写的假设。
将其放在angular初始化之前(例如在html页面的头部)
// Fix base url being case sensitive
(function () {
var base = document.querySelector("base");
var normalized = RegExp(base.href, "i").exec(location.href);
base.href = normalized ? normalized[0] : base.href;
}());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7663 次 |
| 最近记录: |