2013-06-03 1 views
3

저는 Angular를 약 2-3 주 동안 사용하고 있으며 데이터 바인딩 만 사용하고 지시문을 만들려고했습니다. 이제 개체를 서버에 저장하고 싶습니다.각도를 사용하여 엔티티를 만들고 업데이트하는 좋은 방법은 무엇입니까?

도메인 모델은 다음과 같습니다

public class Customer 
{ 
    public int Id { get; set; } 
    public string Code { get; set; } 
    public string CompanyName { get; set; } 
    public string EmailAddress { get; set; } 
    public DateTime BirthDate { get; set; } 
    public string BSNNo { get; set; } 
    public string IdCardNo { get; set; } 
    public bool Deceased { get; set; } 
    public Gender Gender { get; set; } 
    public Title Title { get; set; } // Title is an enum 
    internal bool IsActive { get; set; } 

    public PersonName Name { get; set; } // A value object 
    public PhoneNumber DayPhone { get; set; } // A value object 
    public PhoneNumber OtherPhone { get; set; } 

    public virtual Address Address { get; set; } // A value object 
    public virtual Address PostallAddress { get; set; } 
} 

가 지금은 대응하는 HTML 양식을 만든 내가이 양식을 제출하면, 그것은 각도에 의해 처리됩니다. 그러나 지금 나는이 양식을 저장하는 것이 최선의/권장되는 방법이 무엇인지 궁금합니다.

는 참고 : 우리는 ASP.NET MVC 4

+0

$ rest를 기반으로 $ rest를 사용해야합니다. http://docs.angularjs.org/api/ngResource.$resource –

+1

가능한 [서버에서 데이터를 가져 오는 권장 방법] (http://stackoverflow.com)/questions/11850025/recommended-way-of-the-server-from-the-server) – Stewie

+0

@Stewie 중복 된 것처럼 보이지만, 나는'$ resource'의 사용에 신경 쓰지 않습니다. – Martijn

답변

7

을 사용하는 우리는 $resource 갈 수있는 좋은 방법으로 찾을 수 있습니다. $httpBackend 서비스를 사용하면 손쉽게 테스트 할 수 있습니다. 우리에게는 다음과 같은 것이 있습니다. 그것은 우리를 위해 잘 작동합니다. 조금 더 제어하려는 경우 언제든지 $http 서비스로 되돌아 갈 수 있습니다.

보기

<!DOCTYPE html > 

<html ng-app="myApp"> 
<head> 
</head> 
<body ng-controller="CustomerController"> 
    <form name="form" novalidate> 
     <input type="text" ng-model="customer.name" required /> 
     <input type="text" ng-model="customer.address" required /> 
     <button ng-click="add(customer)">Save</button> 
    </form> 
    <script src="~/Scripts/angular.js"></script> 
    <script src="~/Scripts/angular-resource.js"></script> 
    <script src="~/Scripts/app/app.js"></script> 
    <script src="~/Scripts/app/services/customerResource.js"></script> 
    <script src="~/Scripts/app/controllers/CustomerController.js"></script> 

</body> 
</html> 

서비스 :

myApp.factory('customerResource', function($resource){ 
    var resource = $resource('/data/customer/:id', { id: '@id' }, { 'put' : {method:'PUT' } }); 

    return { 
    getAll : function(){ 
     return resource.query(); 
    }, 
    add : function(customer){ 
      return resource.save(customer); 
    }, 
    update : function(customer){ 
      return resource.put({ id: customer._id }, customer); 
    }, 
    remove : function(id){ 
      return resource.remove({ id: id }); 
    } 
    }; 
}); 

컨트롤러 :

myApp.controller('CustomerController', function($scope, customerResource) { 

    $scope.customer = {}; 

    $scope.customers = customerResource.getAll(); 

    $scope.add = function(customer){ 
    $scope.customers.push(customerResource.add(customer)); 
    } 

    $scope.update = function(customer){ 
    customerResource.update(customer); 
    } 

    $scope.remove = function(customer){ 
    customerResource.remove(customer._id); 
    $scope.customers.splice($scope.customers.indexOf(customer), 1); 
    } 
}); 

아주 기본적인 테스트 :

describe('customerResource', function(){ 
    beforeEach(module('myApp')); 

    describe('getAll', function(){ 

    it('should issue a GET request to /data/customer', inject(function(customerResource, $httpBackend){ 
     $httpBackend.expectGET('/data/customer').respond([{ level: '5'}]); 

     var customers = customerResource.getAll(); 
     $httpBackend.flush(); 

     expect(customers[0].level).toBe('5'); 
    })); 

    it('should return an array of custoemrs', inject(function(customerResource, $httpBackend){ 
    $httpBackend.when('GET', '/data/customer').respond([{ level: '5'}, { level: '6'}]); 

    var customers = customerResource.getAll(); 
    $httpBackend.flush(); 

    expect(customers[0].level).toBe('5'); 
    expect(customers[1].level).toBe('6'); 
    })); 
}); 

MVC 액션는 (ADD - MVC 모델 바인더는 VM에 html로 PARAMS 구문 분석 작업 할 것) :

[HttpPost] 
public ActionResult Customer(Customer customer) 
{ 
     // add the customer to the database or whatever 
} 

뷰 모델을 :

public class Customer 
{ 
    public string Name { get; set; } 
    public string Address { get; set; } 
} 

HTTP 요청은 다음과 같습니다.

Request URL:http://mywebsite/data/customer 
Request Method:POST 
Status Code:200 OK 
Request Headersview source 
Accept:application/json, text/plain, */* 
Accept-Encoding:gzip,deflate,sdch 
Accept-Language:en-GB,en;q=0.8,en-US;q=0.6 
Cache-Control:no-cache 
Connection:keep-alive 
Content-Length:30 
Content-Type:application/json;charset=UTF-8 
Host:mywebsite 
Origin:http://mywebsite 
Pragma:no-cache 
Request Payloadview source 
    {name:somename, address:someaddress} 
    address: "somename" 
name: "someaddress" 

HTH

+0

코드를 보내 주셔서 감사합니다. 나는 백 엔드가 어떻게 생겼는지에 대해서만 궁금해. 제 말은'/ data/customer/: id'가 가리키는 곳은 어디입니까? 이 백엔드는'getAll','add','update','delete' 메소드 이름과 일치합니까? – Martijn

+0

문서는 HTTP 동사를 제공합니다 (http://docs.angularjs.org/api/ngResource.$resource#Returns). 따라서 고객 이름이 HttpGet 또는 HttpPost 인 추가 작업을 수행하면됩니다. 내가 사용하는 백엔드는 노드입니다. –

+0

일부 백엔드 세부 정보로 답변을 업데이트했습니다. 각도면을 설정 한 다음 크롬에서 네트워크 탭을 열고 그 탭으로 재생합니다. –

3

breeze.js에서 살펴 본다보십시오 - 그것은 몇 가지 편리한 변경 내용 추적을 포함하고 또한 쿼리가 실제로 서버를 실행하는 중 하나로, OData/WebAPI 서비스를 쿼리하는 닷넷의 LINQ 스타일의 구문이 -측면. 그것은 $ 자원과 같지만 스테로이드에 관한 것입니다.

+0

+1. 유일한주의 사항은 IE8 이하에서 angularjs와 작동하지 않는다는 것입니다. http://stackoverflow.com/questions/14238134/breeze-and-angular-todo-app-does-not-work-with-ie-8/14244011# comment19764078_14244011 –

관련 문제