【问题标题】:AngularJS request model before another model create [NodeJS]AngularJS 在另一个模型创建之前请求模型 [NodeJS]
【发布时间】:2016-02-05 23:51:56
【问题描述】:

我正在尝试在 MEAN 堆栈上创建简单的 webapp。

我想创建属于 Exposition 的 Offer,但不知道如何在调用 createOffer 之前请求 Exposition。

这是我的代码

$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 模型。

谢谢。

【问题讨论】:

  • 有具体问题吗?问题比较模糊
  • @charlietfl 问题是如何在创建子模型之前加载父模型。 ExpositionResource.findExposition($state.params.expId); - 此代码不起作用
  • “不起作用” 不是正确的问题描述。我们不知道是否正在发出请求,是否抛出错误,findOffer() 是什么,或者它是否失败。从开发工具控制台提供更好的故障排除详细信息
  • @charlietfl 正在发出请求。没有错误。当 OfferResource.query 被调用时,它只返回一个模型 - Offer。如果我将它与 findExposition 方法的响应结合起来,我将在一个 json 对象中获得 2 个模型(对象)。那么,该如何应对。我是角度和节点的新手,但我想了解如何连接两个模型。

标签: javascript angularjs node.js mongodb


【解决方案1】:

您需要使用承诺链来执行此操作。我并不完全清楚您的资源对象是如何工作的(因为我使用 $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
    })
})

【讨论】:

  • 帮了我!谢谢!
猜你喜欢
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多