Angularjs factory data exchange

I wrote one factory to exchange data between controllers. Here's an example

.factory('sharedData', function () {
        var property = {
            title: '',
            color: ''
        };

        return {
            getTitle: function () {
                return property.title;
            },
            setTitle: function (title) {
                property.title = title;
            },
            getColor: function () {
                return property.color;
            },
            setColor: function (color) {
                property.color = color;
            }
        };

      

I am using a controller to set data to a factory with.

sharedData.setTitle("title");

      

but when i try to call:

console.log(sharedData.getTitle());

      

I am getting an empty string. I have included the service in the controller correctly. any help is appreciated.

Edit: Sorry to have missed one important information. I am setting data after successful REST call code like below.

var req =
            {
                method: 'GET',
                url: "/titleName"
                headers: {
                    'Content-type': 'application/json'
                }

            };
            $http(req)
                .success(function (response, status)
                {
                    console.log(status);
                    console.log(response[0].name); 
                    sharedData.setTitle(response[0].name);
                    sharedData.setColor(response[1].color);

                })
                .error(function (response, status)
                {
                });

      

The Json response looks like this:

[{"name":"Name"},{"color":"red"}]

      

console.log on a successful callback gives the correct answer as Name. Thanks to

+3


source to share


1 answer


// EDIT

And I see that you are using the async method. So yes, you have to return the promise and decide its success.

Since the controller doesn't know if it's asynchronous or not, it just expects a value.

Therefore, while the service is fetching data, the controller is already requesting data.

and then an empty string will be sent to you.

When you return a promise, you can resolve it in your routing or in your controller.



// Plunkr is old because the data has changed on the question Hi, I've created a really small plunkr.

.controller('har', function(sharedData) {
   sharedData.setTitle("test")
   console.log(sharedData.getTitle())
   sharedData.setTitle("test2")
   console.log(sharedData.getTitle())
});

      

http://plnkr.co/edit/CvKgKtGmjCDxtk4dcbtv?p=preview

Check your console

I used your factory and a simple controller and to me it looks like it works.

Do you have any other dependencies on it or do you use it in a different way.

0


source







All Articles