0

I have this factory:

app.factory('user', function($http) {
    var state; // logged state

    function login(data) {
        $http.post('/login', {..}).success(function(data) {
            this.state = 1;

        });
        console.log(this.state); // undefined
        return this.state;
    }

    return {
        login: login
    }
});

When I try to use it inside a controller:

app.controller('TestCtrl', function(user) {
    this.login = function() {
        alert(user.login(this.data)); // undefined
    };
});

What am I doing wrong? I've got same code in other project and it's working there.

0

1 Answer 1

1

this in the success callback does not refer to the service. That's why you got an undefined, besides the fact that the console.log is outside the callback.

You should have better results if you cache this at the beginning of the service:

var service = this;

And in the callback, store state in service:

service.state = 1;
Sign up to request clarification or add additional context in comments.

2 Comments

tried, but also not working because I should use promises
Indeed, login should return the $http promise, and you could process the api response in user.login(..).then(...). The purpose of my answer was to alert you on the this problem.

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.