尝试将 html5Mode 与 ui-router 一起使用时出现上述错误。谁能指出我做错了什么?

TypeError: Cannot read property 'replace' of undefined
    at bd (angular.js:10555)
    at Object.<anonymous> (angular.js:11403)
    at l.$get.l.$digest (angular.js:14222)
    at l.$get.l.$apply (angular.js:14493)
    at angular.js:1449
    at Object.e [as invoke] (angular.js:4182)
    at d (angular.js:1447)
    at sc (angular.js:1467)
    at Jd (angular.js:1361)
    at HTMLDocument.<anonymous> (angular.js:26086)
angular.js 中的那个段是:
10554 function trimEmptyHash(url) {
10555   return url.replace(/(#.+)|#$/, '$1');
10556 }

路由文件:
(function(){

    'use strict';

    angular
        .module('app')
        .config(routes);

        routes.$inject = ['$stateProvider', '$locationProvider'];

        function routes($stateProvider, $locationProvider) {

            // Configure app states
            $stateProvider

                .state('app', {
                    abstract: true,
                    templateUrl: 'modules/app/app.html',
                    controller: 'AppController'
                })

                .state('app.home', {
                    url: '/',
                    templateUrl: 'modules/home/index.html'
                });

            $locationProvider.html5Mode(true);
        }
})();

我已经在 html 中设置了基本网址:
<base href="/app/" />

最佳答案

我遇到了同样的问题,在我的情况下,传递给 trimEmptyHash() 的未定义“url”参数最终来自于 $location 上的 $$absUrl 属性没有被初始化的事实。进一步挖掘,似乎 $$absUrl 通常在 $$compose() 方法中初始化,该方法通常从 $$parse() 调用,而 $$parse() 通常从 $$parseLinkUrl() 方法调用。这是 $$parseLinkUrl() (查看 Angular 1.4.1):

this.$$parseLinkUrl = function(url, relHref) {
  if (relHref && relHref[0] === '#') {
    // special case for links to hash fragments:
    // keep the old url and only replace the hash fragment
    this.hash(relHref.slice(1));
    return true;
  }
  var appUrl, prevAppUrl;
  var rewrittenUrl;

  if ((appUrl = beginsWith(appBase, url)) !== undefined) {
    prevAppUrl = appUrl;
    if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
      rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
    } else {
      rewrittenUrl = appBase + prevAppUrl;
    }
  } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
    rewrittenUrl = appBaseNoFile + appUrl;
  } else if (appBaseNoFile == url + '/') {
    rewrittenUrl = appBaseNoFile;
  }
  if (rewrittenUrl) {
    this.$$parse(rewrittenUrl);
  }
  return !!rewrittenUrl;
};

在我的例子中,最后的“if”子句没有触发对 $$parse 的调用,因为“rewrittenUrl”从来没有得到一个值,因为中间的 if/else if 子句都没有解析为 true。就我而言,这是因为我用来提供应用程序的 url (CompanyName/admin.html) 实际上高于我为应用程序设置的基本 Href (CompanyName/admin/),所以没有一个条件解析为 true .一旦我将基本 Href 更改为 CompanyName/,我就不再遇到此问题。

或者,您可以在位置原型(prototype)上初始化 $$absUrl,或等待来自 Angular 的某种修复 - watch this issue,并查看 joelmdev 在 3 月 30 日提出的解决方法。

关于angularjs - 类型错误 : Cannot read property 'replace' of undefined,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29261782/

10-12 14:29
查看更多