Search code examples
javascriptc#jsonangularjsangular-resource

Set controller variable by calling c# webservice from angular with the use of $resource


I have a problem with using the JSON data which is comming from a service. The backend is written in c# and the frontend in AngularJS.

I am not able to use the object as I want in the Angular controller.

So, here is my api restful service in C#

[Route("v1/environment")]
    public IHttpActionResult GetEnvironment()
    {
        var env = new Environment(WebConfigurationManager.AppSettings["Env"]);
        return this.Ok(env);
    }

Then, here is my angular service:

module.factory('Environment', [
    '$resource',
    function ($resource) {
        return $resource('/MorpheusApi/v1/environment', {}, {
            getEnv: {method: 'GET', isArray: false}
        });

    }
    ]);

Then for testing purpose I created also this service:

 module.factory('Env', [
    'Environment',
    function (Environment) {
        return {
            getEnv: function () {
                var s = Environment.getEnv();
                var e = angular.fromJson(s);
                return e;
            }
        };
    }
    ]);

Then I would use it in controller like this:

$scope.envLocal = Env.getEnv();

Then in the ui, with this

<p>Environment Local: {{envLocal}}</p>
    <p>Environment Local Env: {{envLocal.Env}}</p>

I am getting the following output, which is fine I think :)

Environment Local: {"Env":"testText"}

Environment Local Env: testText

But when I now want to let's say provide just the testText from the controller to the ui, I would do something like this:

    var result = Env.getEnv();
$scope.envLocal = result.Env;

But this is then not working.. I tried it also with angular.toJson.. angular.fromJson, but I am not getting anything then in the UI.. Why? How can I use the object properly in the controller, for example if I want to use it in an if or whatever..

Is this even possible?


Solution

  • You can write your factory like this also so you don't need to write two different services.

    module.factory('Environment', ['$resource',
        function ($resource) {
            var api = $resource('/MorpheusApi/:action/:subaction', {}, {
                getEnv: {
                    method: 'GET',
                    params: {
                       action: "v1",
                       subaction:"environment"
                    },
                    isArray: false
                }
            });
            return {
                getEnv: function () {
                    return api.getEnv().$promise;
                }
            };
        }
    ]);
    

    After that You just need to inject this service into the controller and you can call function easily.

    Environment.getEnv()
                    .then(function (response) {
                        //If you wants to perform any logic on response object then you can do here and after that you can assign to scope variable
                        // You can write this logic in service too
                        $scope.envLocal = response;
                    });
    

    You can call the service just I stated above so as $resource is returning promise your scope object will set on successfully call of api and no need to call $scope.$apply() here.

    Suppose you have two different like

    /MorpheusApi/v1/environment

    /MorpheusApi/v2/environment

    You can configure two routes like this call the function as per your need.

    module.factory('Environment', ['$resource',
            function ($resource) {
                var api = $resource('/MorpheusApi/:action/:subaction', {}, {
                    getEnv: {
                        method: 'GET',
                        params: {
                           action: "v1",
                           subaction:"environment"
                        },
                        isArray: false
                    },
                    getEnvV2: {
                        method: 'GET',
                        params: {
                           action: "v2",
                           subaction:"environment"
                        },
                        isArray: false
                    }
                });
                return {
                    getEnv: function () {
                        return api.getEnv().$promise;
                    },
                    getEnvV2: function () {
                        return api.getEnvV2().$promise;
                    }
                };
            }
        ]);
    

    For more information of configration and understanding you can read this Explanation of configration and working of $resource