Angular JS:URL 参数出现在 `#!/` 之前并且没有出现在 $location.search() 中

shr*_*ans 6 javascript angularjs angular-routing

我正在将其他人制作的一个现有的小型 Angular JS 应用程序集成到一个不是用 Angular 构建的现有网站中。

所有 Angular JS 应用程序文件都保存在一个完全独立的目录中,然后用户可以单击链接将它们带到该子目录的索引。例如:

<a href="/path/to/angular-app/?returnUrl=/original/location">Login.</a>
Run Code Online (Sandbox Code Playgroud)

正如您在上面看到的,我需要传递一个名为returnUrl. 然后我需要在 Angular JS 应用程序中获取这个值,使用:

<a href="/path/to/angular-app/?returnUrl=/original/location">Login.</a>
Run Code Online (Sandbox Code Playgroud)

然而,这实际上返回一个空对象。我认为这是因为 Angular JS在 URL 参数之后附加#!/login在URL 上,如下所示:

example.com/path/to/app?returnUrl=/original/location/#!/login
Run Code Online (Sandbox Code Playgroud)

如果我在浏览器中修改 URL,将returnUrl参数移动到 URL 的末尾并刷新页面,它会工作并$location.search()返回{returnUrl: "/original/location/"}. 但是,据我所知,我无法在我的网站上更改此参数,因为该参数是指向 Angular JS 应用程序的链接的一部分,#!/login随后会自动添加。

我是新的 AngularJS,所以请尽可能清楚地解释:

  1. 这里发生了什么?为什么是URL参数之前#!/login
  2. 为什么这会阻止$location.search()返回任何东西?如果我将参数移动到结果 URL 的末尾,它就可以工作。
  3. 我能做些什么来解决这个问题?

ada*_*101 4

这里发生了什么?为什么URL参数在#!/login之前?

您可以在#!之前考虑查询字符串参数。作为服务器端参数,以及#!后面的querystring参数 作为客户端参数。这是完全有效的:

http://example.com?serverParam=client1#!angularRoute?angularParam=someValue
Run Code Online (Sandbox Code Playgroud)

服务器参数允许您配置如何从服务器提供页面,然后在提供服务器页面并加载 Angular 应用程序后,使用客户端参数来提供特定 Angular 应用程序所期望的内容。

为什么这会阻止 $location.search() 返回任何内容?如果我将参数移动到结果 URL 的末尾,它就会起作用。

因为在将值移到那里之前,没有为客户端参数指定任何内容。

我可以做什么来解决这个问题?

  1. 您可以更改链接,就像您修改它们以使它们工作一样:<a href="example.com/path/to/app/#!/login?returnUrl=/original/location">Login.</a>或者复制参数,以便它在服务器和客户端上都可用<a href="example.com/path/to/app/?returnUrl=/original/location#!/login?returnUrl=/original/location">Login.</a>
  2. 您可以注入并从中 $window获取服务器端值$window.location.search
  3. 您可以注入$location并使用$location.absUrl()

以下是如何从服务器端参数设置客户端参数的示例:

http://example.com?serverParam=client1#!angularRoute?angularParam=someValue
Run Code Online (Sandbox Code Playgroud)
var app = angular.module('YOURAPPNAME', []);

app.run(['$location', function($location) {
  // I'm going to fake out the url so it runs in the SnippetEditor.
  var url = "example.com/path/to/app?returnUrl=/original/location/#!/login"; //$location.absUrl();
  var hashbangIdx = url.indexOf('#!');
  var serverStr = hashbangIdx > -1 ? url.substring(0, hashbangIdx) : url;
  var qIdx = serverStr.indexOf("?");
  var p = qIdx > -1 ? serverStr.substring(qIdx).split(/[&||?]/) : [];
  for (var i = 0; i < p.length; i += 1) {
    if (p[i].indexOf('=') > -1) {
      var param = p[i].split('=');
      $location.search(param[0], param[1]);
    }
  }
}]);

app.controller('MainCtrl', ['$scope', '$location', function($scope, $location) {
  $scope.params = $location.search();
}]);
Run Code Online (Sandbox Code Playgroud)