gpt4 book ai didi

AngularJS:如何等待 $resource 完成?

转载 作者:行者123 更新时间:2023-12-03 07:57:35 24 4
gpt4 key购买 nike

我有一个 Controller :

app.controller('ProductDetailCtrl', ['$scope', '$q', '$resource', 'Product', function($scope, $q, $resource, Product) {
$scope.product = {};

$scope.init = function(id)
{
$scope.product = Product.get({productId: id});

}

$q.all([$scope.product.$promise]).then(function() {
$scope.selected_color = $scope.product.products_colors[0];
});

// $scope.selected_color = $scope.product.products_colors[0];

}]);

还有一个工厂:

app.factory('Product', ['$resource', function($resource) {
return $resource("/api/products/:productId", {}, {
query: {method: 'GET', isArray: true},
});
}]);

但是,当我加载页面时,它给了我这个:

Error: $scope.product.products_colors is undefined @http://localhost:3000/assets/products/controllers/productscontroller.js?body=1:11:5 qFactory/defer/deferred.promise.then/wrappedCallback@http://localhost:3000/assets/angular.js?body=1:11499:15 qFactory/ref/<.then/<@http://localhost:3000/assets/angular.js?body=1:11585:11 $RootScopeProvider/this.$get</Scope.prototype.$eval@http://localhost:3000/assets/angular.js?body=1:12609:9 $RootScopeProvider/this.$get</Scope.prototype.$digest@http://localhost:3000/assets/angular.js?body=1:12421:15 $RootScopeProvider/this.$get</Scope.prototype.$apply@http://localhost:3000/assets/angular.js?body=1:12713:13 bootstrap/doBootstrap/<@http://localhost:3000/assets/angular.js?body=1:1420:9 invoke@http://localhost:3000/assets/angular.js?body=1:3919:7 bootstrap/doBootstrap@http://localhost:3000/assets/angular.js?body=1:1419:1 bootstrap@http://localhost:3000/assets/angular.js?body=1:1432:5 angularInit@http://localhost:3000/assets/angular.js?body=1:1345:5 @http://localhost:3000/assets/angular.js?body=1:21818:5 jQuery.Callbacks/fire@http://localhost:3000/assets/jquery.js?body=1:3100:1 jQuery.Callbacks/self.fireWith@http://localhost:3000/assets/jquery.js?body=1:3212:7 .ready@http://localhost:3000/assets/jquery.js?body=1:3424:3 completed@http://localhost:3000/assets/jquery.js?body=1:3454:3


return logFn.apply(console, args);

我如何等到 $resource 完成加载?我想根据 Product.get(..) 的结果设置我的 $scope 变量之一。我知道 Product.get(..) 正在返回并使用 products_colors 属性对象,因为 console.log 是这么说的

最佳答案

使用回调:

Product.get({productId: id}, function(data) {
$scope.product = data;
});

关于AngularJS:如何等待 $resource 完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25001736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com