使用资源服务时如何传入参数?

win*_*ler 35 angularjs

一个非常新秀的问题:

我正在尝试使用工厂方法构建资源对象:

.factory('Magazines', [function ($resource) {

    var url = document.URL;
    var urlArray = url.split("/");
    var organId = urlArray[urlArray.length-1];

    return $resource('http://localhost/ci/api/magazines/:id', {
        loginID : organEntity,
        password : organCommpassword,
        id : organId
    });
  }])
Run Code Online (Sandbox Code Playgroud)

这种方法很简单,因为所有参数都是预定义的,organEntity和organCommpassword是在标签内定义的.

现在,对于不同的资源对象,我需要在调用工厂时传入参数.

我想这个资源对象的调用代码应该如下所示:

.controller('ResrouceCtrl', function($scope, Magazines) {
      $scope.magazines = Magazines.query();
});
Run Code Online (Sandbox Code Playgroud)

我知道query()方法可以添加参数: Magazines.query(params, successcb, errorcb);

我想知道我是否只传入参数,我可以在工厂获得参数吗?如何在factory方法中指定这样传入的参数?

例如,现在假设我不能再从url获取organId,我需要从我的控制器传递它,如何在工厂方法中接收organId?


这是我的资源js:

.factory('MagComments', function ($resource) {


    return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
      loginID : organEntity,
      password : organCommpassword,
      id : '@magId' //pass in param using @ syntax
    });
  })
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

$scope.magComments = MagComments.query({magId : 1});
Run Code Online (Sandbox Code Playgroud)

我试图传入参数,但它会导致错误

Chr*_*ola 47

我想我看到了你的问题,你需要使用@语法来定义你将以这种方式传递的参数,我也不确定你做什么的loginID或密码你似乎没有在任何地方定义它们并且它们没有被使用作为URL参数,它们是作为查询参数发送的吗?

根据我目前所看到的情况,这是我可以建议的:

.factory('MagComments', function ($resource) {
    return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
      loginID : organEntity,
      password : organCommpassword,
      id : '@magId'
    });
  })
Run Code Online (Sandbox Code Playgroud)

@magId字符串将告诉资源替换:idmagId您将其作为参数传递的对象上的属性.

我建议阅读这里的文档(我知道它有点不透明)非常仔细,并看到最后的例子,这应该有很多帮助.


Max*_*tin 8

我建议你用provider.如果您想在使用之前先配置它(针对服务/工厂),那么提供是好的

就像是:

.provider('Magazines', function() {

    this.url = '/';
    this.urlArray = '/';
    this.organId = 'Default';

    this.$get = function() {
        var url = this.url;
        var urlArray = this.urlArray;
        var organId = this.organId;

        return {
            invoke: function() {
                return ......
            }
        }
    };

    this.setUrl  = function(url) {
        this.url = url;
    };

   this.setUrlArray  = function(urlArray) {
        this.urlArray = urlArray;
    };

    this.setOrganId  = function(organId) {
        this.organId = organId;
    };
});

.config(function(MagazinesProvider){
    MagazinesProvider.setUrl('...');
    MagazinesProvider.setUrlArray('...');
    MagazinesProvider.setOrganId('...');
});
Run Code Online (Sandbox Code Playgroud)

现在控制器:

function MyCtrl($scope, Magazines) {        

        Magazines.invoke();

       ....

}
Run Code Online (Sandbox Code Playgroud)