1

I have the following factory:

app.factory('clientFactory', function ($http) {
    var factory = {};

    factory.getClients = function () {
        var url = "/tracker/api/client";
        $http.get(url).then(function (response) {
            return response.data;
        });
    };

    factory.getClient = function (id) {
        // TODO
    };

    factory.insertClient = function (firstName, lastName, city) {
        // TODO
    };

    factory.deleteClient = function (id) {
        // TODO
    };

    return factory;
});

And the controller:

app.controller('ClientController', function ($scope, clientFactory) {
    $scope.clients = [];

    init();

    function init() {
        $scope.clients = clientFactory.getClients();
    }

    $scope.insertCustomer = function () {
        // TODO
    };

    $scope.deleteCustomer = function (id) {
        // TODO
    };
});

In my controller, 'clients' is always null. I've tried a couple of other approaches like what I see here but I got an error that 'success cannot be called on null' and if I make it past that error, my success function is never called.

What am I missing here?

1 Answer 1

1

In your controller, you are treating the getClients method as if it were synchronous. Remember that when you do $http.get, a promise is returned. You need to return that promise to the controller, so it can call .then with a method which will handle a successful result.

Your getClients method needs to look like this:

factory.getClients = function () {
    var url = "/tracker/api/client";
    return $http.get(url);
};

And I believe your init method needs to look like this:

function init() {
    clientFactory.getClients().then(function(response) {
        $scope.clients = response.data;
    });
}

Try that out!

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

2 Comments

Excellent! Thanks very much... coming from the jQuery world, things were either async or not and there was some magic there (at least to me). The promises stuff is new to me.
Yeah promises take a little bit to wrap your head around, but once you understand them you will love them. They are a huge part Angular, so you will be seeing them much more often!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.