使用AngularJS执行REST请求时遇到一些问题。
我用PHP(Laravel)完成了服务器部分,我用POSTMAN测试它,它工作正常。我只有POST /表达式,我发送json像{"expression":"(2+5)"}
,我会得到json像{"expression":"(2+5)","result":"7"}
,当我做几个POST请求时,我需要在result.html页面上连接结果。我为路由提供写了app.js,我有contoller.js
//post expression
myApp.controller('expressionController', ['$scope', 'postExpressionFactory', 'getExpressionFactory','$location',
function ($scope, postExpressionFactory,getExpressionFactory, $location) {
$scope.postNewExpression = function () {
$scope.results = postExpressionFactory.evaluate({'expression':$scope.expression});
console.log($scope.results.expression);
console.log($scope.results.result);
};
}]);
并在services.js中设有工厂
//post factory
myServices.factory('postExpressionFactory', ['$resource',
function ($resource) {
return $resource('../server.php/expression', {}, {
evaluate: {method: 'POST', headers: {'Content-Type': 'application/json'}, isArray: false}
});
}]);
并拥有调用此帖子请求的html
<form>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label class="control-label">Enter expression</label>
<div class="input-group">
<span class="input-group-addon">=</span>
<input class="form-control" type="text" id="expression" name="result" ng-model="expression" ng-required="true">
<span class="input-group-btn">
<button class="btn btn-default" type="button" ng-click="postNewExpression()">Calculate</button>
</span>
</div>
<h2>Results</h2>
<div class="list-group" ng-repeat="res in results">
<a class="list-group-item">
<h4 class="list-group-item-heading">{{res.expression}}</h4>
<h4 class="list-group-item-heading">{{res.result}}</h4>
</a>
</div>
</div>
</div>
</div>
</form>
Angular运行正常,我想我没有让json正确,当我在mozilla-&gt;网络中执行此操作时,我看到我已经完成了POST请求,并且我得到了json respone结果:“7”,表达式:( 2 + 5)。我怎样才能得到这个结果 - &gt; 7在results.expression,results.result?
答案 0 :(得分:1)
您的$ scope.results对象被定义为具有两个属性,但是当您在ng-repeat中迭代它时,您尝试访问不存在的字符串的属性,因此它会无声地失败。
// your results object:
$scope.results = postExpressionFactory.evaluate({'expression':$scope.expression});
// so your object looks like this:
{
expression: something,
result: somethingElse,
}
您尝试访问它的方式:
<div class="list-group" ng-repeat="res in results">
<a class="list-group-item">
<h4 class="list-group-item-heading">{{res.expression}}</h4>
<h4 class="list-group-item-heading">{{res.result}}</h4>
</a>
</div>
通过打印对象来查看HTML中的错误:
<div class="list-group" ng-repeat="res in results">
{{ result }}
<a class="list-group-item">
<h4 class="list-group-item-heading">{{res.expression}}</h4>
<h4 class="list-group-item-heading">{{res.result}}</h4>
</a>
</div>
// what you probably want is an array for the results, then push onto the array
$scope.results = [];
// push
$scope.results.push(postExpressionFactory.evaluate({'expression':$scope.expression}));