我正在尝试在MEAN堆栈上创建简单的webapp。
我想创建属于博览会的商品,但在调用createOffer之前不知道如何请求展示。
这是我的代码
$stateProvider
.state('offer', {
url: "/exposition/:expId/offer/",
templateUrl: 'app/exposition/listOffers.tpl.html',
controller: 'OffersController'
})
.state('offercreate', {
url: "/exposition/:expId/offer/create/",
templateUrl: 'app/exposition/createOffer.tpl.html',
controller: 'OffersController'
})
.state('offerview', {
url: "/exposition/:expId/offer/:id/",
templateUrl: 'app/exposition/detailsOffer.tpl.html',
controller: 'OffersController'
});
和控制器
offerApp.controller('OffersController', ['$scope', '$resource', '$state', '$location', 'OfferUpdateService', 'Upload',
function ($scope, $resource, $state, $location, OfferUpdateService, Upload) {
var OfferResource = $resource('/offer/:id');
var ExpositionResource = $resource('/exposition/:id');
$scope.offerUpdateService = new OfferUpdateService();
var loadOffers = function () {
return OfferResource.query(function (results) {
$scope.offers = results;
if ($state.params.id) {
$scope.findOffer($state.params.id);
}
if ($state.params.expId) {
ExpositionResource.findExposition($state.params.expId);
}
});
};
}
]);
这是正确的想法吗?我想在Offer之前加载Exposition,然后将exposition.id映射到Offer模型。
谢谢。
答案 0 :(得分:2)
您需要使用承诺链来执行此操作。我并不完全清楚你的资源对象是如何工作的(因为我使用$ q& $ http代替,但文档表明它们返回带有RESTful API的对象)。以下是按顺序请求2个资源的示例:
var OfferResource = $resource('/offer/:id');
var ExpositionResource = $resource('/exposition/:id');
ExpositionResource.get({id:123}).$promise.then( function(rsp, rspHeaders){
//set your model ID how you want
model.id = rsp.id
//now hit your next API in the sequence
OfferResource.query({id:model.id}).$promise.then( function(rsp2, rspHeaders2){
//you can do this again if need be to a 3rd sequential call
})
})