【问题标题】:How to contact a non-standard API using Angular ngResource如何使用 Angular ngResource 联系非标准 API
【发布时间】:2016-10-31 14:33:32
【问题描述】:

如果我尝试搜索特定的非 ID 字段,我正在使用的 API 需要非标准的 where 子句。我需要的端点是:

http://127.0.0.1:4001/api/testusers/findOne?userName=Anton

所以这将在 testusers 表中找到我的第一条记录,其列 (userName) = 'Anton'。

我的标准服务是:

angular.
  module('shared.testUser').
  factory('TestUser', ['$resource',
    function($resource) {
      return $resource('http://127.0.0.1:4001/api/testusers/:id', {id:'@id'},//parameters
            {
                update: {
                      method: 'PUT' // To send the HTTP Put request when calling this custom update method.
                }
                 
            });
    }
  ]);

我的调用函数是:

    self.checkUsersEntryDirection = function(){ //NOT WORKING
      self.testuser = TestUser.get({ username: 'anton' }, function() {
        console.log(angular.toJson(self.testuser));
      }); // get() returns a single entry
    }

显然这不起作用,我不能使用标准的 get 方法。谁能想到这是如何实现的?

【问题讨论】:

    标签: angularjs ibm-cloud


    【解决方案1】:

    您可以创建一个二级工厂TestUserByName,并进行以下更改:

    angular.
      module('shared.testUser').
      factory('TestUserByName', ['$resource',
        function($resource) {
          return $resource('http://127.0.0.1:4001/api/testusers/findOne?userName:username', null,
                {
                    update: {
                          method: 'PUT' // To send the HTTP Put request when calling this custom update method.
                    }
    
                });
        }
      ]);
    

    【讨论】:

      【解决方案2】:

      使用两个参数调用get操作方法:

      var params = {id: "findOne", username: "anton"};
      
      self.checkUsersEntryDirection = function(){
        self.testuser = TestUser.get(params, function() {
          console.log(angular.toJson(self.testuser));
        }); // get() returns a single entry
      }
      

      id 参数将覆盖默认值,username 参数将作为查询字符串添加。

      来自文档:

      参数对象中的每个键值首先绑定到 url 模板(如果存在),然后将任何多余的键附加到 ? 之后的 url 搜索查询。

      给定一个模板/path/:verb 和参数{verb:'greet', salutation:'Hello'} 得到URL /path/greet?salutation=Hello

      --AngularJS ngResource $resource Service API Reference

      【讨论】:

        猜你喜欢
        • 2021-04-10
        • 1970-01-01
        • 1970-01-01
        • 2017-11-26
        • 2013-06-01
        • 2015-05-28
        • 2017-05-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多