0

我在服务器端使用 WebAPI:

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

角:

$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 } });
}])

我看到的不是数字 101,而是承诺: {"0":"1","1":"0","2":"1"}

如何实现回调以查看对象而不是承诺?

4

2 回答 2

1

问题不在于您的回调实现。问题是您正在使用$resource,它旨在与返回JSON 格式字符串的 RESTful API 资源一起使用,该服务返回没有结构化格式的纯文本。

解决方案1:

如果您能够更改 WebAPI 服务器返回的数据格式,您可以让它返回一个简单的 JSON 对象。它可能是这样的:

{"value": "101"}

然后,您$resource将或多或少地按原样工作。

解决方案2:

如果你不能或不想修改你的 WebAPI 响应,你可以在 Angular中使用,$http而不是:$resource

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

这将用于检索纯文本响应,而无需像这样修改响应数据$resource

工作 Plunker 演示了这两种方法

于 2014-05-20T04:25:25.250 回答
1

确保您包含来自 webapi 的 application/json 标头和 json 数据,看起来您没有。

于 2014-05-20T06:31:18.667 回答