1

First I have the factory like this:

app.factory('getApiUrl', function (httpq, $q) {

    var obj = {};
    obj.getResponse = function (hurl) {
        var promise = $q.defer();

        httpq.get(hurl).then(function (data) {
            //obj = data.data;
            promise.resolve(data.data);
        })

        return promise.promise;

    }
    return obj;
});

Then I create controller and call factory like this:

app.controller('mainController', function ($scope, httpq, $q, getApiUrl) {
    $scope.message = "Main Content";
    var namees = new Array();
    var testc = getApiUrl.getResponse(hurl);
    $scope.names = testc.data;
});

But it is not working.

Nima Derakhshanjan
  • 1,380
  • 9
  • 24
  • 37
chi nguyen
  • 45
  • 6
  • It not working, i just try this.. – chi nguyen Dec 11 '15 at 07:01
  • `hurl` is not defined. You're also using a promise antipattern: your returned promise will never be rejected, even if there is an error. The function body should just be `return httpq.get(hurl).then(function (response) { return response.data;});`. Read http://blog.ninja-squad.com/2015/05/28/angularjs-promises/ – JB Nizet Dec 11 '15 at 07:01

1 Answers1

2

getResponse method returns promise object. You need to provide callbacks for when response is resolved. The proper usage then would be:

app.controller('mainController', function ($scope, httpq, $q, getApiUrl) {
    $scope.message = "Main Content";
    var namees = new Array();
    getApiUrl.getResponse(hurl).then(function(data) {
        var testc = data;
        $scope.names = testc.data;
    });
});

As a sidenote, you should also get rid of redundant $q.defer in service since httpq.get(hurl) is already a promise:

obj.getResponse = function (hurl) {
    return httpq.get(hurl).then(function (data) {
        return data.data;
    });
}
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • It working, but why can not using like some var testc = getApiUrl.getResponse(hurl); because i see some sourcode using like this in angularjs for example http://plnkr.co/edit/gUqz1Q0jUfXhkAJThTaK?p=preview – chi nguyen Dec 11 '15 at 07:05
  • Because you are making AJAX request and this is asynchronous operation. Code just doesn't "wait" until response loads and simply returns "undefined". So you need to either use callback or promise. Check [this](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) for more details. – dfsq Dec 11 '15 at 07:07
  • i just try: obj.getResponse = function (hurl) { return httpq.get(hurl).then(function (data) { return data.data; }); } – chi nguyen Dec 11 '15 at 07:15
  • @chinguyen the example you posted uses angular 1.0.1, which used to support the usage of promises in view expressions. It isn't the case anymore for a looooong time. 1.0.1 is 3,5 years old. We're now at 1.4.8. – JB Nizet Dec 11 '15 at 07:16
  • Ok, for my mistake, because i just read and research about angular, Thank you. – chi nguyen Dec 11 '15 at 07:19