javascript - 在另一个服务调用中使用一个服务调用的结果(Angular)

标签 javascript angularjs

我当前正在调用服务方法以返回我的 Angular 应用程序中的玩家配置文件。然后,我需要利用另一个服务方法调用的结果立即“处理”一些返回的数据。我想知道下面是否正确构建了我的 Controller ,或者我是否应该在我的 playersService$promise 分辨率内进行 codesService 调用而是打电话。

注意:下面的 Controller 是我的实际 Controller 的简化版本。实际控制者涉及“按摩”十几个要素。

'use strict';

angular.module('gameApp')
  .controller('ProfileController', ProfileController);

ProfileController.$inject = ['$routeParams', 'playersService', 'codesService'];

function ProfileController($routeParams, playersService, codesService) {
  var vm = this;
  var playerId = $routeParams.playerId;
  var codes;

  var getCodes = function() {
    codesService.get().$promise.then(function(data) {
      codes = data;
    });
  };

  var getProfiles = function() {
    playersService.getProfiles({
      playerId: playerId
    }).$promise.then(function(profiles) {
      for (var i = 0; i < profiles.length; i++) {
        profiles[i].name = codes.MSP[profiles[i].MSPkey].name;
      }
      vm.profiles = profiles;
    });
  };

  var init = function() {
    getCodes();
    getProfiles();
  };

  init();
}

最佳答案

您的 Controller 应该非常简单,并且可以直接准确地获取它所需要的内容。

.controller("ProfileController", function(profileService, $routeParams){
  var vm = this;
  var playerId = $routeParams.playerId;

  profileService.getProfiles(playerId)
    .then(function(profiles){
       vm.profiles = profiles;
    });
});

profileService 应该只返回整齐捆绑和打包的所有内容。

它将需要使用其他服务(即 codesServiceplayersService)作为依赖项。而且,正如我在评论中提到的(以及他们的答案中的其他一些内容),您可以并行调用对 codesServiceplayersService 的调用,但是您必须等待两者都完成。

.factory("profileService", function($q, codeService, playersService){
  var svc = {
    getProfiles: function(playerId){
      $q.all({ 
          players: getPlayers(playerId),
          codes:   getCodes()
        })
        .then(function(data){
           var players = data.players;
           var codes = data.codes;

           return DoMassaging(players, codes);
        })
    }
  };

  return svc;
});

确保 getPlayers()getCodes() 返回各自的 Promise。

关于javascript - 在另一个服务调用中使用一个服务调用的结果(Angular),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31658776/

相关文章:

javascript - 使用 javascript 的返回值作为 struts if 标签中的条件

javascript - 当 $.each 和 array.splice(i) 放在一起时,JQuery 处理数组超出索引错误

javascript - jQuery.getScript 适用于本地但不适用于 GitHub Pages

javascript - 如何在 Angular js验证中添加自己的类名

javascript - 如何将 ngMouseMove 事件计算与我的 div 对齐

html - 将 ng-repeat 与 Bootstrap 导航栏元素一起使用

javascript - ajax提交后隐藏div

javascript - 如何在 Chrome 扩展中删除事件监听器

javascript - 如何在 Angular 中显示小数点后 2 位数字,但将其存储在小数点后 4 位

javascript - Google Drive OAuth 在某些浏览器上触发 origin_mismatch