gpt4 book ai didi

javascript - 带有端点的 Angular 服务

转载 作者:行者123 更新时间:2023-12-03 04:21:11 27 4
gpt4 key购买 nike

我刚刚开始 Angular,我想创建一个简单的服务,可以使用我的 api 生成数据。

我有一条返回此的路线:

/ranking/:id 

返回视频游戏结果的排名

[
{
position: 1,
user: 1234,
score: 150
}, {
position: 2,
user: 5678,
score: 100
}
...
]

然后

/users?ids=id1,id2,id3

返回用户数组

[
{
id: 1234,
firstName: 'John',
lastName: 'Doe'
},
...
]

我想要做的是创建一个函数,该函数可以通过组合端点来显示用户所在的对象数组,这样我就可以获得这样的对象:

 [
{
position: 1,
score: 150,
firstName: 'John',
lastName: 'Doe'
},
...
]

感谢您的帮助!

最佳答案

这可能有帮助

first inject $q in your service, so you can execute two or more async calls at once.


var rankingsProm = $http.get('rankings endpoint');
var usersProm = $http.get('users endpoint');

$q.all([rankingsProm, usersProm]).then(function (responses) {
console.log("result of $q.all", responses)
// responses[0] => rankings and responses[1] => users
console.log(mergeRankingWithUsers(responses[0], responses[1]))
})


function mergeRankingWithUsers (rankings, users) {
var merged = rankings.map(function (ranking) {
var index = users.findIndex(function (user) { return user.id === ranking.user; });
ranking.firstName = index > -1 ? users[index].firstName : 'unknown';
ranking.lastName = index > -1 ? users[index].lastName : 'unknown';
return ranking;
})
return merged;
}

关于javascript - 带有端点的 Angular 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43939968/

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