angularjsngresource

Passing a parameter to a $resource?


I have a controller that that looks like this:

(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;                        
    });        
}}());

The user is authenticated by the time they reach this point in the app. So, the user's info is available.

I have a backend API that takes a user's name and returns the names of branches that user is authorized to. I can paste the URL into my browser, along with a valid user name, and get expected results. I'm trying to use that API in my branchResource:

(function () {
"use strict";

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

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

My problem, though, is that I don't know how to pass the vm.user to the branchResource from the controller. Can someone point me in the right direction?


Solution

  • Create the $resource object with:

    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")        
    }}
    

    Call the $resource object with:

    branchResource.query({"federatedUserName": vm.user}, function (data) {
        vm.branches = data;                        
    });
    
    //OR
    
    vm.branches = branchResource.query({"federatedUserName": vm.user});
    

    It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

    Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the ?.

    For more information, see AngularJS ngResource $resource API Reference.