我正在尝试使用一个非常简单的CRUD应用程序。它涉及一个带有单个文本框的表单。通过框发布的所有条目都应显示在文本框下方的网格中。
一切都很好,但除非刷新页面,否则网格不会以新条目更新。我正在使用localhost:3000上运行的loopback api和localhost:9000上的角度应用程序。数据库是MySQL。
如果我使用MEAN堆栈,相同的代码按预期工作。现在我们必须从我的应用程序支持mySQL和解耦API。 这是控制器。
angular.module('dashboardApp')
.controller('StateCtrl', function ($scope, $http) {
$scope.formData = {};
$scope.baseUrl = '//localhost:3000/api/v1/states';
$http.get($scope.baseUrl).success(function(states) {
$scope.states = states;
});
$scope.create = function() {
$http.post($scope.baseUrl, $scope.formData)
.success(function(states) {
$scope.states = states;
})
.error(function(states) {
console.log('Error: ' + states);
});
};
});
这是观点。
<form class="form-inline" role="form" data-ng-submit="create()">
<div class="form-group">
<label class="sr-only" for="name">State</label>
<input type="text" class="form-control" id="name" placeholder="Enter state" ng-model="formData.name">
</div>
<button type="submit" class="btn btn-default">Enter</button>
</form>
<table class="table table-striped">
<tr ng-repeat="state in states">
<td>{{state.name}}</td>
</tr>
</table>
感谢任何帮助。只是一个注释:我也尝试过使用服务/资源而不是$ http。
答案 0 :(得分:2)
我认为这里的问题是$http.get
返回一个数组,$http.post
函数中的$scope.create
返回一个对象。
$scope.states
数组中。或.. .. 从$http.post
请求中返回一个数组,并将其分配给$scope.states
angular.module( 'dashboardApp') .controller('StateCtrl',function($ scope,$ http){ $ scope.formData = {}; $ scope.baseUrl ='// localhost:3000 / api / v1 / states';
$http.get($scope.baseUrl).success(function(states) {
$scope.states = states; // this returns an array
});
$scope.create = function() {
$http.post($scope.baseUrl, $scope.formData)
.success(function(states) {
//$scope.states = states; // this return an object
// Do this
$scope.states.push(states);
})
.error(function(states) {
console.log('Error: ' + states);
});
};
});
注意:或者您可以在$http.post
答案 1 :(得分:0)
正如您所做的Cross-Origin Resource Sharing(CORS)是添加所需HTTP Access-Control-Allow-Origin标头的API服务?如果不是,浏览器将阻止响应。向$http.get()
添加错误回调也应该有助于检测错误。
答案 2 :(得分:0)
我同意@Maurice你可能遇到跨域问题,你有两个端口涉及9000和3000.如果你期待的数据是json,你可以尝试添加你的网址
$scope.jsonpUrl = $scope.baseUrl+"?callback=JSON_CALLBACK";
$http.jsonp($scope.jsonpUrl)
.success(function(states) {
$scope.states = states;
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("Error:", data);
});
尝试一下,让我们知道。干杯