gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:02:29 25 4
gpt4 key购买 nike

我当前正在调用服务方法以返回我的 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/

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