Angularjs $ resource get / post返回相同的结果

时间:2014-06-17 14:44:46

标签: javascript angularjs asp.net-web-api

我是一个全新的角色,所以我可能做错了。我的查询返回一个像它应该的对象数组。然后我做了一个点击事件来测试帖子..点击我的web api就好了......但是然后它从我的get中返回相同的数组。我猜这是缓存的吗?为什么我的帖子会显示我之前获得的结果?

编辑 - 抱歉,我本可以更清楚。当我运行我的saveTest方法时,会触发一个帖子并保存我的数组,但结果是'结果'该save的变量是我原来的数组。

app.directive('referenceSection', function () {
 return {
   restrict: 'E',
   templateUrl: '/app/loanapplication/views/reference-section.html',
   controller: function ($scope, referenceService) {
     $scope.json = angular.toJson($scope.referenceArray);
     $scope.referenceArray = [];

     referenceService.query().$promise.then(function (result) {
       $scope.referenceArray = result;
       }, function () {
       alert("fail");
     });

     $scope.saveTest = function () {
       referenceService.save(angular.toJson($scope.referenceArray)).$promise.then(function (result) {
       var x = result;
       }, function () {
       alert("save fail");
     });
   }
 }
 };
});

服务

app.factory('referenceService', function ($resource) {
 var requestUri = '/api/reference';
 return $resource(requestUri)
});

Web api

public class ReferenceController : BaseController
{

  public HttpResponseMessage Get()
  {
    List<WebReference> references = new List<WebReference>();

    WebReference reference = new WebReference();
    WebReference reference2 = new WebReference();

    reference.Name = "Andrew";
    reference.Relationship = "QuickSupport";
    reference.Id = 1;

    reference2.Name = "Josh";
    reference2.Relationship = "Hansen";
    reference2.Id = 2;

    references.Add(reference);
    references.Add(reference2);

    if (references == null) throw new HttpResponseException(HttpStatusCode.NotFound);

    return Request.CreateResponse<IEnumerable<WebReference>>(HttpStatusCode.OK, references);
  }

  public HttpResponseMessage Post([FromBody]WebReference[] references)
  {
    try
    {
      var msg = new HttpResponseMessage(HttpStatusCode.Created);
      return msg;
    }
    catch (Exception e)
    {
      throw new HttpResponseException(HttpStatusCode.Conflict);
    }
  }
}

}

2 个答案:

答案 0 :(得分:0)

 referenceService.query().$promise.then(function (result) {
   $scope.referenceArray = result;

在此之后,您需要致电$scope.$apply()以通知角度您所做的更改是否受约束。如果我猜错了你的问题。

: - )

答案 1 :(得分:0)

从哪里阅读回复?来自x之外的x不可用于函数,或者错误地将其附加到referenceArray

referenceService.save(angular.toJson($scope.referenceArray)).$promise
.then(function (result) {
  var x = result;
}, function () {
  alert("save fail");
});