如何获得$ http响应并使用服务分配给本地变量?
问题描述:
service.js
angular.module('app')
.service('tableService', [
'$q',
tableService
]);
function tableService($q){
var tableData = [
{
issue: 'Vinayak N',
progress: 100,
// status: 69,
class: 'md-accent'
}
];
}
我想对$ http.get( 'http://localhost:5000/api/studentsList')的呼叫;和response.data分配到一个局部变量资料表中service.js
答
试试这个:
angular.module('app')
.service('tableService', [
'$q','$http',
tableService
]);
function tableService($q, $http){
var tableData = [
{
issue: 'Vinayak N',
progress: 100,
// status: 69,
class: 'md-accent'
}
];
$http.get('http://localhost:5000/api/studentsList').then(function(result){
tableData.data = result.data;
});
}
答
必须在您服务您的变量绑定到你的控制器。
$ http.get( 'http://localhost:500/api/studentList')。然后(函数(RES){ tableService.tableData = RES;});
有很多方法来绑定它们。这真的取决于你如何操纵你的代码。
+0
它不能正常工作 – Inayath
答
首先创建一个服务
angular
.module('app')
.factory('tableService', tableService);
function tableService($q, $http, $cookies) {
return {
tableData: tableData
};
function tableData() {
var d = $q.defer();
$http({
method: 'GET',
url: 'http://localhost:5000/api/studentsList'
}).success(function(response) {
d.resolve(response);
}).error(function(response) {
d.reject(response);
});
return d.promise;
}
}
注:我创建的工厂,你可以做,通过服务也
创建您的控制器,并调用内部控制服务
angular
.module('app')
.controller('tableController', tableController);
function tableController($scope, tableService) {
$scope.tableData = [];
tableData();
function tableData() {
tableService.tableData().then(function(response) {
if (response.success) {
$scope.tableData = response.data;
}
}, function() {
});
}
}
JavaScript是异步你不能这样做。 – Inayath
@Inathath所以,我认为问题在桌子上。它在数据加载之前呈现,对吗? –