【问题标题】:AngularJS callback function not workingAngularJS回调函数不起作用
【发布时间】:2014-05-20 02:53:46
【问题描述】:

我在服务器端使用 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"}

如何实现回调才能看到对象而不是承诺?

【问题讨论】:

  • 看来您在此问题中犯了与 OP 类似的错误:stackoverflow.com/questions/23749148/…(参见:RobM 的回答)您需要使用 @ 而不是尝试将回调作为参数传递,而是987654324@,如$scope.averageQuantity = Quantity.query(queryArgs).then(function(results){ /* console.log(results.data */ })
  • 感谢您的回复,马克。我认为 then() 方法是 jQuery 特定的方法,我没有在这个项目中使用 jQuery(我被要求不要)。我查看了那个链接,我确实错过了一个参数(用于发布数据),它就在成功函数之前。不幸的是,它仍然不起作用。这让我觉得这实际上可能是 $resource 错误配置而不是回调问题?这是我尝试过的:$scope.averageQuantity = Quantity.query(queryArgs, {}, function(returnValue, responseHeaders) { console.log(returnValue); });
  • then 不是 jQuery 特定的。 Angular 包含 $q,以 Q 为 promises 的模式,其中包含一个then 方法。不过,我必须承认我最初的判断是错误的。该问题与回调或承诺无关。我即将发布的答案将说明问题所在。

标签: angularjs asp.net-web-api callback angularjs-factory


【解决方案1】:

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

解决方案 1:

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

{"value": "101"}

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

解决方案 2:

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

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

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

Working Plunker demonstrating both methods

【讨论】:

  • 谢谢你,马克!我通过使用 $http 使用了非常相似的东西,代码如下:$scope.showDetails = function(product) { $scope.selectedProduct = product; $http.get('/api/quantity?productId=' + product.id).then(function (results) { $scope.averageQuantity = results.data; }); };
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多