Search code examples
angularjsasp.net-web-apicallbackangularjs-factory

AngularJS callback function not working


I am using WebAPI on the server side:

    public int Get(int productId)
    {
        //removed the actual logic to simplify the example
        return 101;
    }

The Angular:

$scope.showDetails = function (product) {
    $scope.selectedProduct = product;
    var queryArgs = { productId: product.id };
    $scope.averageQuantity = Quantity.query(queryArgs, function() {
        //callback function
        console.log($scope.averageQuantity); // this shows a promise instead of an actual object
        //and then open modal and pass the $scope as a parameter
    });
};

//the resource:
.factory('Quantity', ['$resource', function ($resource) {
return $resource('/api/quantity', {}, { 'query': { method: 'GET', isArray: false } });
}])

Instead of the number 101 I see the promise: {"0":"1","1":"0","2":"1"}

How can I implement the callback in order to see the object and not the promise?


Solution

  • The issue is not your callback implementation. The problem is that you're using $resource, which is meant for use with RESTful API resources that return JSON formatted strings, with a service that returns plain-text with no structured formatting.

    Solution 1:

    If you're able to change the format of the data your WebAPI server returns, you can have it return a simple JSON object. It could be something like:

    {"value": "101"}

    Then, your $resource will be work more or less as is.

    Solution 2:

    If you can't or otherwise don't want to modify your WebAPI response, you can use $http instead of $resource in Angular:

    $http.get('example', {params: params});

    This will work to retrieve a plain-text response without munging the response data the way $resource does.

    Working Plunker demonstrating both methods