gpt4 book ai didi

javascript - 如何使用 http 响应填充作用域?

转载 作者:行者123 更新时间:2023-12-02 17:24:09 25 4
gpt4 key购买 nike

我遇到的问题是,在页面加载时,API 的响应需要一段时间,并且我的 View (范围)为空。但是,当我来回切换 View 时,组 View (范围)会使用页面加载时从 API 加载的对象进行更新。

我希望能够加载所有数据并使其始终在所有 View 中可用,并在数据可用时动态更新页面加载时的第一个 View (范围)。

我想这是可能的,但我错过了什么?

我的服务:

angular.module('myApp.services', [])
.service('groups', function ($http) {
var groups = [];

// Load the data once from the API
if(!groups.length) {
$http.get('/api/groups')
.then(
function(response) {
groups = response.data;
}
);
}

return {
// For update if new data is available
setData: function(arr) {
groups = arr;
},
// Return all groups
getAll: function () {
return groups;
},
// Get a given group name
getNameById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].name;
}
}
return null;
},
// Get a given group short name
getShortNameById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].short_name;
}
}
return null;
},
getTeamsById: function (id) {
for(var i = 0; i < groups.length; i++) {
if(groups[i].id === id) {
return groups[i].team_ids;
}
}
return null;
}
};
});

我的 Controller :

function GroupsOverviewCtrl($scope, groups) {
// Populate the scope with data
$scope.groups = groups.getAll();
}
GroupsOverviewCtrl.$inject = ['$scope', 'groups'];

最佳答案

处理异步操作的“Angular 方式”是 promise 而不是回调。
它可能是这样的:

.factory('groups', function ($http, $q) {
var groups = [],

return {
setData: function(arr) {
groups = arr;
},
getAll: function () {
if(groups.length) {
return $q.when(groups);
} else {
return $http.get('/api/groups').then(function (response) {
groups = response.data;
return groups;
});
}
},
getNameById: function (id) {...},
getShortNameById: function (id) {...},
getTeamsById: function (id) {...}
};
});

function GroupsOverviewCtrl($scope, groups) {
groups.getAll().then(function (data) {
$scope.groups = data;
});
}
GroupsOverviewCtrl.$inject = ['$scope', 'groups'];

关于javascript - 如何使用 http 响应填充作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23641298/

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