【问题标题】:AngularJS $http url placeholders not being placed with real dataAngularJS $http url 占位符未放置真实数据
【发布时间】:2013-08-11 13:16:20
【问题描述】:

我是 Angular 的新手,并且遇到了一个问题,即我的 $http url 占位符没有被实际数据替换。我想要的是这个:

"/json/:searchType/:userId"

在我使用 $http 调用时被替换为:

"/json/user/123"

相反,根据萤火虫的“网络”标签,我得到了这样的东西:

"/json/:searchType/:userId?userId=123&searchType=user"

我试图创建一个小提琴,但因为我使用来自服务器的不同视图和 json 数据,我不确定如何创建在小提琴中工作的东西,它看起来仍然像我实际在做的一样。我看过this answerthis answerthis answerthis answerthis answer 等等。我很难找到与 $resource 无关的帖子,或者它用于将 url 参数链接到对象参数的 @ 表示法。

为了解释,我使用服务在控制器和我的工厂之间传递 searchTypeaccountId 参数,这实际上执行 $http 请求。

这是我的控制器:

.controller('UserDetailsCtrl', ["$scope", "Search", function ($scope, Search) {
    $scope.result = Search.getUser();
}])

这是我的工厂:

.factory('Search', ["$http", "SearchCriteriaSvc", function($http, SearchCriteriaSvc) {

    var baseUrl = "/json/:searchType/:accountId";

    return {
      getUser: function () {
        return $http.get(baseUrl,
                  {params:
                      {
                        accountId: SearchCriteriaSvc.getAccountId(),
                        searchType: SearchCriteriaSvc.getSearchType()
                      }
                })
                .then(function(result) {
                  return result.data;
                }); 
      }
    }
  }])

最后,我的服务:

  .service('SearchCriteriaSvc', function() {
    var searchType = "",
        userId = "";

    return {
        getSearchType: function () {
            return searchType;
        },
        setSearchType: function(value) {
            searchType = value;
        },
        getUserId: function () {
            return userId;
        },
        setUserId: function(value) {
            userId= value;
        }
    };
  })

我尝试不使用该服务来传递参数(只是手动输入字符串)并且得到相同的结果,所以我认为我的服务不是问题,但是,我不知所措.

任何帮助都会很棒。谢谢!

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    $http 不能以这种方式工作。您必须自己将参数整理到 URL 中。 您可能正在考虑 $resource 允许您预定义 HTTP 请求 URL 及其参数组件,或者 $route 它也允许类似的参数 URL 功能,但在您的角度前端而不是后端的上下文中。 以您传递它们的方式传递的任何参数最终都将作为查询 / GET 样式参数。

    http://docs.angularjs.org/api/ng.$http

    params – {Object.<string|Object>} – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.
    

    【讨论】:

    • 你是对的 - 我不敢相信我错过了。感谢您的快速帮助!
    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 2011-08-01
    • 2011-08-10
    • 2013-09-13
    • 2018-10-25
    • 2016-03-20
    • 2017-02-10
    • 2019-01-26
    相关资源
    最近更新 更多