简体   繁体   English

如何通过多次调用在Angular JS服务或控制器中建立模型数据?

[英]how can I build up model data in Angular JS service or controller with multiple calls?

I need to show the results of multiple calls to a REST server in a page using AngularJS. 我需要在使用AngularJS的页面中显示多次调用REST服务器的结果。

The first call gets the details of a product, which itself contains the IDs of other products. 第一次调用获取产品的详细信息,该产品本身包含其他产品的ID。

I want to render the details of this product, but I also need each of the dependent products to be queried in the back and, and to display some of the details of each on the same page, divided up by category. 我想呈现此产品的详细信息,但我还需要在后面查询每个从属产品,并在同一页面上按类别划分显示每个产品的一些详细信息。

The template code is below 模板代码如下

<div class="span6">
    <div class="well">
        <h2>product details</h2>
    </div>
    <div class="well">
        <h3>{{device.product.brand}} {{device.product.model}}</h3>
        <p>SKU: {{device.product.sku}}</p>

        <div ng-repeat="reltype in ['plan', 'insurance', 'dataallowance']">
            <h3>{{reltype}}</h3>
            <ul>
                <li ng-repeat="rel in relationships | filter: {type:reltype}">
                    <a href="#/product/{{rel.relId}}">{{plan.type}} {{plan.family}}</a>
                    <p> {{plan.marketingMessage}}</p>
                </li>
            </ul>
        </div>
    </div>
</div>

my app.js: 我的app.js:

angular.module('prodcat', ['prodcatServices']).

    config(['$routeProvider', function($routeProvider, $locationProvider) {

        $routeProvider.
            when('/products', {templateUrl: '/prodCatVisualiser/partials/device-list.html', controller: ProductListCtrl}).
            when('/product/:id', {templateUrl: '/prodCatVisualiser/partials/device-detail.html', controller: ProductDetailCtrl}).
            otherwise({redirectTo: '/products'});

    }]);

services.js: services.js:

angular.module('prodcatServices', ['ngResource']).

    factory('Devices', function($resource) {

        return $resource('/prodCatVisualiser/ajax/products');

    })
    .factory('Device', function($resource){

        return $resource('/prodCatVisualiser/ajax/product/:id');

    });

and controllers.js: 和controllers.js:

"use strict";

function ProductListCtrl($scope,Devices) {
    $scope.devices = Devices.query();
}

function ProductDetailCtrl($scope, $routeParams, Device) {
    $scope.device = Device.get({id: $routeParams.id});
}

I've tried changing the productDetailCtrl method to something like this: 我尝试将productDetailCtrl方法更改为如下所示:

function ProductDetailCtrl($scope, $routeParams, Device) {
    var plans = new Array();
    $scope.device = Device.get({id: $routeParams.id}, function($scope, plans) {
        var relationships = $scope.product.relationships;
        for (var i=0; i < relationships.length; i++) {
            var planDetail = Device.get({id: relationships[i].relId}, function($scope, plans){
                plans.push(planDetail);
            });
        }
    });
    $scope.relationships = plans;
}

but to no avail. 但无济于事。 I can't seem to get my head around the asynchronicity of the secondary service calls as a result of the first call. 由于第一个调用,我似乎无法理解辅助服务调用的异步性。

so is the controller (and a single function within) the best place to make all the service calls and put them together? 那么控制器(和其中的单个功能)是进行所有服务调用并将它们组合在一起的最佳位置吗?

or is it better for the template to use controllers or services to make the extra back-end calls when I iterate over the dependent products? 还是在迭代依赖产品时使用模板或控制器来进行额外的后端调用更好? this seems to go against the usual MVC paradigm of the controller putting together the model and then passing it onto the view to be rendered. 这似乎违背了控制器通常的MVC范例,即将模型放在一起然后将其传递到要渲染的视图上。 but Angular is MVC with an asynchronous slant, so maybe not! 但是Angular是具有异步倾向的MVC,所以也许不是!

I would handle this in the service. 我会在服务中处理。 Something along the lines of: 类似于以下内容:

.factory('Device', function($resource){
    var device = $resource('/prodCatVisualiser/ajax/product/:id');
    for (var rel in device.relationships) {
         rel.data = $resource(/prodCatVisualiser/ajax/product/:id).get({id: rel.relId});
    }
    return device;
});

(warning - off the cuff code, probably contains an error somewhere, I haven't had coffee yet...consider as pseudocode) (警告-关闭袖口代码,可能在某个地方包含错误,我还没喝咖啡...考虑为伪代码)

Now what your controller receives will go through three states: 现在,您的控制器收到的内容将经历三种状态:

  1. A promise of the main product data 主要产品数据承诺
  2. A fulfilled promise for the main product data, containing pending promises for each of the relationship products. 主要产品数据的已兑现承诺,其中包含每个关系产品的未决承诺。
  3. A completely fulfilled promise with data for all of the products needing to be displayed. 带有所有需要显示的产品数据的完全兑现的承诺。

Far from breaking MVC, this supports it. 它并没有破坏MVC,反而支持了它。 The view has no need to know that it takes more than one server call to retrieve this information. 该视图无需知道它需要多个服务器调用来检索此信息。 It really gets down to what you consider to be the 'real' controller in this scenario. 在这种情况下,它实际上取决于您认为是“真正”的控制器。 In this layout, it's the service's job to retrieve the relevant model, and everyone downstream of that just needs to worry about what to do with it. 在这种布局中,检索相关模型是服务的工作,而下游的每个人都只需要担心如何处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在同一个控制器angular js中使用多个服务 - Use multiple service in same controller angular js 我可以在Angular JS的1 Div中拥有多个控制器吗? - Can I have multiple controller inside1 Div in Angular JS? 如何从Angular的$ http服务中将数据发布到WebAPI控制器? - How can I POST data to a WebAPI controller from Angular's $http service? 如何获取多个Angular JS路由来共享一个控制器实例? - How can I get multiple Angular JS routes to share a single controller instance? 如何从控制器调用角度服务? - How can I invoke an angular service from a controller? 如何为角度控制器和服务编写茉莉花测试? - How can I write jasmine test for angular controller and service like this? 如何将数据从Angular控制器传递到JavaScript或Paper.js - How can I Pass data from an Angular Controller to JavaScript or to Paper.js Angular.js:在ng-repeat内的子控制器中,如何传播模型更改 - Angular.js: In child controller inside ng-repeat, how to propagate up model changes 如何使用angular js在任何服务/控制器中调用另一个服务变量数据 - How to call another service variable data in any service/controller using angular js Angular JS SPA:如何使用Angular Controller SPA调用Angular服务? - Angular JS SPA: How to Angular Controller SPA to call Angular service?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM