将参数传递给$ resource?

时间:2017-12-28 19:51:31

标签: angularjs ngresource

我有一个看起来像这样的控制器:

(function() {
angular
    .module("main")
    .controller("HomeCtrl",
        ["branchResource",
        "adalAuthenticationService",
        HomeCtrl]);

function HomeCtrl(branchResource, adalService){
    var vm = this;                
    vm.copyrightDate = new Date();        
    vm.user = adalService.userInfo.userName;

    // right here, can I insert the vm.user from above
    // as a parameter to the resource's query?
    branchResource.query(function (data) {
        vm.branches = data;                        
    });        
}}());

用户在应用中达到此点时进行身份验证。因此,用户的信息可用。

我有一个后端API,它接受用户的名称并返回用户被授权的分支的名称。我可以将URL粘贴到我的浏览器中,并附上有效的用户名,并获得预期的结果。我试图在branchResource中使用该API:

(function () {
"use strict";

angular
    .module("common.services")
    .factory("branchResource",
    ["$resource", branchResource]);

function branchResource($resource){
    return $resource("/api/user/GetAllUserBranches?federatedUserName=:user")        
}}());

我的问题是,我不知道如何将vm.user传递给控制器​​中的branchResource。有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

使用:

创建$resource对象
function branchResource($resource){
    ̶r̶e̶t̶u̶r̶n̶ ̶$̶r̶e̶s̶o̶u̶r̶c̶e̶(̶"̶/̶a̶p̶i̶/̶u̶s̶e̶r̶/̶G̶e̶t̶A̶l̶l̶U̶s̶e̶r̶B̶r̶a̶n̶c̶h̶e̶s̶?̶f̶e̶d̶e̶r̶a̶t̶e̶d̶U̶s̶e̶r̶N̶a̶m̶e̶=̶:̶u̶s̶e̶r̶"̶)̶ ̶
    return $resource("/api/user/GetAllUserBranches")        
}}

使用:

调用$resource对象
branchResource.query({"federatedUserName": vm.user}, function (data) {
    vm.branches = data;                        
});

//OR

vm.branches = branchResource.query({"federatedUserName": vm.user});

重要的是要意识到调用$resource对象方法会立即返回一个空引用(对象或数组,具体取决于isArray)。从服务器返回数据后,将使用实际数据填充现有引用。

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

有关详细信息,请参阅AngularJS ngResource $resource API Reference