我是angularJS的新手。我一直在使用mysql显示所有客户。所以,我在cotroller和service中写道:
app.controller('CustomersController', function ($scope, customersService, $http) {
init();
function init() {
$scope.customers = customersService.getCustomers();
}
});
app.service('customersService', function ($http) {
this.getCustomers = function () {
return customers;
};
// my issue is here
$http.get("app/server/read.php")
.success(function(data){
var customers = data;
});
});
在php中我写道:
$result = mysqli_query($con,"SELECT * FROM customers");
$return_arr = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$rowArr = array(
'id' => $row['id'],
'firstName' => $row['firstname'],
'lastName' => $row['lastname'],
'address' => $row['address'],
'city' => $row['city']
);
$return_arr[] = $rowArr;
}
echo json_encode($return_arr);
php将json数组返回为:
[{"id":"36","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"37","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"38","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"39","firstName":"","lastName":"","address":"","city":""},{"id":"40","firstName":"asd","lastName":"asd","address":"","city":"asd"}]
我不明白如何将这个json对象数组放入变量customers
,因为当我将这个数组直接写入变量customers
时,它就可以了。即。
var customers = [{"id":"36","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"37","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"38","firstName":"asdasd","lastName":"asdasd","address":"","city":"asdasd"},{"id":"39","firstName":"","lastName":"","address":"","city":""},{"id":"40","firstName":"asd","lastName":"asd","address":"","city":"asd"}]
但是,在获得get方法结果成功后,我无法动态地设置它。
答案 0 :(得分:1)
从您的服务返回$http
承诺,然后在.success回调中设置您的$ scope属性。
app.controller('CustomersController', function ($scope, customersService, $http) {
init();
function init() {
customersService.getCustomers().success(function(data){
$scope.customers = data;
});
}
});
app.service('customersService', function ($http) {
this.getCustomers = function () {
return $http.get("app/server/read.php");
};
});