I try to get data from 2 jsons :
1st 'names.json':
[
{
"name": "AAAAAA",
"down": "False"
},
{
"name": "BBBBBB",
"down": "45%"
},
{
"name": "CCCCC",
"down": "12%"
}
]
Second 'data.json'
[
{
"data": "25-12-2014"
}
]
Javascript:
app.service('service', function($http){
this.getNames = function () {
var data = $http.get('data,json', { cache: false});
var names = $http.get('names.json', { cache: false});
return names;
return data;
};
});
app.controller('FirstCtrl', function($scope, service) {
var promise = service.getNames();
promise.then(function (data) {
$scope.datas = data.data;
console.log($scope.datas);
});
})
HTML
div ng-controller="FirstCtrl"
<table>
<tbody>
<tr ng-repeat="name in datas">
<td>{{name.name}}</td>
<td>{{name.data}}</td>
</tr>
</tbody>
</table>
</div>
In my console.log and table i only see data from json "names.json", but i want also see data from "data.json" Thanks in advance.
You should return both the promise together, you can't have two return in a single function. In this case $q.all
would help.
Code
//inject $q in service function
this.getNames = function () {
var data = $http.get('data,json', { cache: false});
var names = $http.get('names.json', { cache: false});
return $q.all([data, names]);
};
Controller
var promise = service.getNames();
promise.then(function (data) {
$scope.datas = data[0].data;
$scope.names = data[1].data;
});
Change your code to this
app.service('service', function($http) {
return{
getData : function(){
return $http.get('data,json', { cache: false });
},
getNames : function(){
return $http.get('names.json', { cache: false });
}
}
});
app.controller('FirstCtrl', function($scope, service, $q) {
$q.all([service.getData(), service.getNames()]).then(function(response){
$scope.data = response[0].data;
$scope.names = response[1].data:
});
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.