我试图检索两个数据,一个来自API和我的json,当我拨打电话时,我只收到第二个电话。
json 1
[
{
"id": 1,
"img":"images/clientlogos/21747.jpg"
},
{
"id": 2,
"img": "images/clientlogos/FMI.png"
}
]
来自APi的jason @来电话
[
{
"id": 1,
"name": "Enough",
"forecasted": 22,
"budget": 40,
"hoursspent": 3.53999997675419,
"currentcosts": 965.393393660635,
"xerototal": 2800
},
{
"id": 2,
"name": "Fad Ltd",
"forecasted": 96.5,
"budget": 300,
"hoursspent": 199.91000029631,
"currentcosts": 66234.589716303,
"xerototal": 176472
},
]
我的工厂
app.factory('myFactory', function($http){
return{
client: function(callback){
$http({
method: "GET",
url: "http://www.outleading.co.za/api/api/clientdashboarddata",
cache:true
}).then(callback);
},
list: function(callback){
$http({
method: "GET",
url: "data/Client.json",
cache:true
}).then(callback);
}
};
});
我的控制器
app.controller('myController', function ($scope, $http, myFactory) {
myFactory.client(function (response) {
var data = response.data;
$scope.myClients = data;
})
myFactory.list(function(response){
var data= response.data;
$scope.myClients= data;
})
};
}
})
我的HTML
在我的ng-repeat里面我希望从我的json获得{{client.img}}并从api调用获得{{client.clientname}}
<div class="card client-card" ng-repeat="client in myClients>
<div class="client-logo">
<img ng-src="{{client.img}}" alt="{{client.name}}">
</div>
</div>
所以任何帮助都会得到很大的帮助。
答案 0 :(得分:0)
修改工厂以返回承诺,它为您提供了灵活性
app.factory('myFactory', function ($http) {
return {
client: function () {
return $http({
method: "GET",
url: "http://www.outleading.co.za/api/api/clientdashboarddata",
cache: true
});
},
list: function () {
return $http({
method: "GET",
url: "data/Client.json",
cache: true
});
}
};
});
使用$q.all()
并等待所有承诺完成
app.controller('myController', function ($scope, $http, myFactory, $q) {
$q.qll(myFactory.client(), myFactory.list()).then(function (result) {
$scope.myClients = result[0].data;
var images = result[1].data;
$scope.myClients.forEach(function(client){
// find index of image for client
var idx= images.findIndex(function(x){
return x.id == client.id
});
client.name = images[idx].name;
})
});
});
答案 1 :(得分:0)
您正在调用两个API并覆盖输入。
app.controller('myController', function ($scope, $http, myFactory) {
myFactory.client(function (response) {
var data = response.data;
$scope.myClients = data; //Same variable
})
myFactory.list(function(response){
var data= response.data;
$scope.myClients= data; //Same variable
})
};
}
})
不是在两个调用中的$ scope.myClients中保存数据,而是使用一些不同的变量名。我猜第二个应该是$ scope.lists