简体   繁体   English

angular:将数据传递到$ resource服务

[英]angular: passing data to $resource service

Hi there I write a service of $resource for connecting the api. 嗨,我编写了$ resource服务来连接api。 here is the code in service.js 这是service.js中的代码

.factory('selfApi2', function ($resource, localStorageService) {
var AB = {
  data: function (apiURL, header, data, params) {
    return $resource("http://localhost:4000/api" + apiURL, null, {
      update: {
        method: 'POST',
        headers: header,
        data: data,
        params: params
      }
    });
  }
};
return AB;
})

in my controller.js 在我的controller.js中

var header = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var myData = {
'phone': '12345678'
};
selfApi2.data('/tableName',header,{where:{"name":"kevin"}).update(myData, function(result){
console.log("update Kevin's phone succeed",result);
})

it works. 有用。 But why the variable myData should put inside the update() part rather than the data() part? 但是,为什么变量myData应该放在update()部分而不是data()部分中?

I think it's because "data" is a function that returns object of $resource. 我认为这是因为“数据”是一个返回$ resource对象的函数。 Try the scenario below: 请尝试以下情形:

    // service
    .factory('api', function ($resource) {
      var api = {};

      api.issues = $resource("http://localhost:4000/api/issues");

      api.users = $resource("http://localhost:4000/api/users", {}, {
        update: {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        },
      });

      return api;
    })

    // controller
    api.users
      .update({where:{name:'kevin'}})
      .$promise.then(function(success) {
        // DO SOMETHING
      });

    ...

    api.issues.query().$promise.then(
      function(success) {
        // DO SOMETHING
      });

In your case, the data() is a function which will just create a ReST resource which would expose rest apis get save query remove delete as default. 在您的情况下, data()是一个函数,它将仅创建一个ReST资源,该资源将公开rest api get save query remove delete作为默认值。

So in this data() call you are just creating the rest resources. 因此,在此data()调用中,您只是在创建其余资源。 Passing myData with this function would not make any sense. 使用此函数传递myData没有任何意义。 The data() call would return the Resource instance which will have your update api function which accepts the parameters. data()调用将返回Resource实例,该实例将具有接受参数的update api函数。

And, passing your data at api construction time does not make sense. 而且,在api构建时传递数据没有任何意义。

Here is the complete reference 是完整的参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM