首先我想澄清,我没有使用网络服务访问数据。 我的数据库(php)和 angularjs UI 位于同一服务器上。
在 AngularJs 服务中,我向 interface.php(Database) 发送 http Get 请求,它返回 json 格式。我不知道如何实际解析数据并将其发送到 Controller ?
这里清晰的代码:)
var app=angular.module("app.chart.ctrls",['ngSanitize']);
Controller
app.controller("registrationCtrl",["$scope","$location","logger","registerService",function($scope,$location,logger,registerService){
$scope.data= registerService.getYears();
**how to parse the data is it correct format or not ? in Controller**
}
**Service**
app.factory('registerService', function ($http,$q,$log) {
return {
getYears:function () {
var deferred = $q.defer();
$http({
method : "GET",
url : "interface.php",
}).success(function(data){
**** How to Return the data from here to Controller ***
})
},
}
});
接口(interface).php
最佳答案
1 - 首先在 Controller 中定义一个对象,稍后您可以将其用作 http 响应的存储,如下所示:
app.controller("registrationCtrl",["$scope","$location","logger","registerService",function($scope,$location,logger,registerService){
$scope.data = {};
// fire your servise function like this :
registerService.getYears($scope);
}
2- 在您的服务中:
app.factory('registerService', function ($http) {
return {
getYears:function (scope) {// scopes comes from your controller
$http({method : "GET",url : "interface.php"})
.success(function(data){
scope.data = data;!!!!!!
})
}
}
});
到目前为止已经完成并且可以工作了;
但是如果你想使用某种 promise ,你可以这样做:
在你的 Controller 中:
.
.
.
$scope.data = {};
// fire your servise function like this :
var promise = registerService.getYears();
promise.then(function(msg){
$scope.data = msg.data[0];
});
.
.
.
在您的服务中:
app.factory('registerService', function ($http) {
return {
getYears:function () {
var promise = $http({method : "GET",url : "interface.php"});
}
return promise ;
});
关于php - Angularjs如何获取服务中$http响应返回的Json格式的解析数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24306069/