1

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

nicer way of writing the service.. will rewrite it. :)
You can configure other api also in the same service if your's routes have similar prefix path. Let me know if you want some example I will post.
sure, more examples are always welcome to understand more :) thanks
how does that behave when you are doing $querry or $post? will i then create again methods for that like getEnv and so on?
if you have different method types and api path then just configure as I shown in example . Read article you can access default methods by default with $resource on configured path.
1

I think it's due to the fact that you're attempting to set the scope variable after calling getEnv. You may have to use an angular promise to do that

Does something like this work?

var promise = Env.getEnv();
promise.then(function(res) {
    $scope.envLocal = res.Env;
}, function(err) {});

You might need to wrap your $scope.envLocal in an $apply also, not sure though...

 $scope.$apply(function () { 
    $scope.envLocal = res.Env; 
 });

6 Comments

ya, you are right,, with that it is working, forgot to say that i tried this also.. is this the only way? are there other options to do it? When i want to have it in a service, i do not want to do things like this in all controllers.. Do you have an other idea?
and the $apply would be inside the promise?
If you return a promise in a service with all the logic in the promise and return just the Env property, you can do something like myService.myFunc().then(function(env){ $scope.env = env; })
You wouldn't need the $apply if you return the promise and set the $scope variable in the return function of the promise (see above comment)
@damir All http requests are inherently asynchronous. You do not get the results of a GET request immediately. There is always going to be some lag time between the client request and the server response. Setting a variable equal to the response before the server has returned it makes the variable null or undefined. You can't think synchronously in an asynchronous environment. This is why promises are used.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.