编辑(根据问题更新)
问题
控制器与工厂之间的交互设计方式脆弱且容易出错。请参阅下面注释的代码:
// factory
app.factory('companies', ['$http', function($http) {
data = [];
for (let i = 1; i < 11; i++) {
// you CANNOT control when this is going to return
$http.get('https://examplepage.com/wp-json/wp/v2/categories?per_page=50&page=' + i)
.then(function(response) {
// so this doesn't push to `data` synchronously, this DOES NOT
// guarantee you when you return data, every response.data will be there
data.push(response.data);
console.log('data', data);
},
function(err) {
return err;
});
}
// this will always be returned empty ([], as you initialized it) because
// the async responses (commented above) haven't arrived when this lint his hit.
return data;
}]);
// controller
$scope.companies = companies; // so, companies will always be [] (empty array)
解决方案
您应该强烈考虑将实现工厂的方式更改为如下方式:
想法:
- 不调用端点
x(11)次获取550个项目(50 * 11次)
- 在工厂中提供一个函数(
getCompanies),它接受一个itemsPerPage 和一个page 参数,这样你就可以在你想要的页面中获取尽可能多的项目。即:要获得 550 个项目,您应该调用它:companies.getCompanies(550);
- 任何想要联系公司的控制者拨打
companies.getCompanies
代码:
// factory
app.factory('companies', ['$http', function($http) {
function fnGetCompanies(itemsPerPage, page) {
var ipp = itemsPerPage || 50; // 50 default
var page = page || 0; // 0 default page
// return the promise instead of data directly since you cannot return the value directly from an asynchronous call
return $http
.get('https://examplepage.com/wp-json/wp/v2/categories?per_page=' + ipp + '&page=' + page)
.then(
function(response) {
// and then return the data once the promise is resolved
return response.data;
},
function(err) {
return err;
}
);
}
// provide a `getCompanies` function from this factory
return {
getCompanies: fnGetCompanies
}
}]);
// controller
// get 550 items starting from 0
companies.getCompanies(550, 0).then(function(companies) {
$scope.companies = companies;
});
补充说明
记住You cannot return from an asynchronous call inside a synchronous method
原帖
您可以先使用Array.prototype.reduce 将多数组结构转换为单个数组,如下所示:
$scope.companies = companies.reduce(function(prevArr, currentArr) { return prevArr.concat(currentArr);}, []);
这会转换这样的结构:
[
[{id: 1, name: 'A'}, {id: 2, name: 'B'}, {id: 3, name: 'C'}],
[{id: 4, name: 'D'}, {id: 5, name: 'E'}, {id: 6, name: 'F'}]
];
进入这个:
[{"id": 1,"name": "A"},{"id": 2,"name": "B"},{ "id": 3,"name": "C"},{"id": 4,"name": "D"},{"id": 5,"name": "E"},{"id": 6,"name": "F"}]
简单演示:
var companies =[
[{id: 1, name: 'A'}, {id: 2, name: 'B'}, {id: 3, name: 'C'}],
[{id: 4, name: 'D'}, {id: 5, name: 'E'}, {id: 6, name: 'F'}]
];
console.log(companies.reduce(function(prev, current) { return prev.concat(current);}, []));