.factory('dataServices',dataServices);
dataServices.$inject =['$http'];
function dataServices($http){
var services = {
getType :getType
}
return services;
function getType(){
return $http.get('/src/server/data/data.php')
.then(function(response){
return response.data.filter(function(item){
return item.loai;
});
})
}
这是控制器中的代码
Shell.$inject =['dataServices'];
function Shell(dataServices){
var vm = this;
vm.types=dataServices.getType();
console.log(vm.types)
}
这是文件php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require '/../server/connectdb.php';
$row = array();
$sql = "SELECT * FROM item";
if($result){
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode($rows);
}
mysqli_close($conn);
这是我的json文件
[{"id":"1","masp":"CPUB028","tensp":"Block CPU EK Supre","hangsx":"INTEL","loai":"CPU","img":"item1.jpg","gia":"70","gt":null},
{"id":"2","masp":"CPUIT5","tensp":"CPU INTEL CORE I5","hangsx":"INTEL","loai":"CPU","img":"item14.jpg","gia":"400","gt":null}]
在console.log中我得到response.data.filter不是功能。我哪里错了?
答案 0 :(得分:0)
这里可能会出现一些问题:
application/json
内容类型其中一个条件必须为true才能认为它应该解析json文件:https://github.com/angular/angular.js/blob/master/src/ng/http.js#L140
您的console.log无法正常工作,因为$ http会返回一个承诺,因此您需要执行dataServices.getType().then(console.log)
之类的操作。
答案 1 :(得分:0)
您可以尝试使用getType()的工厂方法中的代码,如下所示,
return $http.get('/src/server/data/data.php').then(function(response){
var returnValue = [];
angular.forEach(response.data.value, function(item){
returnValue.push(item.loai);
});
return returnValue;
}