내맘대로 살기🎉

[angularJS] 서비스&팩토리 본문

개발자의 길/AngularJS

[angularJS] 서비스&팩토리

해림😶 2017. 4. 26. 13:51
서비스

1
2
3
4
5
myApp.service('Math', function () {
  this.multiply = function (x, y) {
    return x * y;
  };
});
 
- Math 콘텍스트(콘텍스트라는 명칭이 맞는지 의심됨.)에 multiply라는 메소드를 추가한다.


1
2
3
4
5
6
7
myApp.controller('MainCtrl', ['$scope', function ($scope) {
    var a = 12;
    var b = 24;
 
    // 결과는 288
    var result = Math.multiply(a, b);
}]);
- controller안에 서비스를 위와 같이 사용할 수 있다.


1
2
3
4
5
6
7
8
// Math를 주입한다
myApp.controller('MainCtrl', ['$scope', 'Math', function ($scope, Math) {
    var a = 12;
    var b = 24;
 
    // 결과는 288
    var result = Math.multiply(a, b);
}]);

- 하지만, controller안에 콘텍스트(콘텍스트라는 명칭이 맞는지 의심됨.)를 넣어주어야 컴파일 에러가 발생하지 않거나 컨트롤러가 동작함.

위의 function($scope)란 의존성 주입 방법을 뜻함.



팩토리


팩토리를 이용하여 서비스를 만드는 건 아주 간단하고, 서비스를 만드는 것과 비슷하다.


1
2
3
4
5
6
7
8
9
10
myApp.factory('Server', ['$http', function ($http) {
  return {
    get: function(url) {
      return $http.get(url);
    },
    post: function(url) {
      return $http.post(url);
    },
  };
}]);
 
- 위와 같이 만들어주면 된다. 코드를 보면 어떤 동작을 하는지 얼추 이해가 된다.



1
2
3
4
5
6
myApp.controller('MainCtrl', ['$scope', 'Server', function ($scope, Server) {
    var jsonGet = 'http://myserver/getURL';
    var jsonPost = 'http://myserver/postURL';
    Server.get(jsonGet);
    Server.post(jsonPost);
}]);

- Angular의 XHR을 래핑한 코드라고 한다. 컨트롤러에 의존성을 주입한 다음 간단하게 사용 가능.

* XHR : Ajax에서 XMLHttpRequest(HTTP request를 서버에 보낸다)



* 출처 : http://soomong.net/blog/2014/01/20/translation-ultimate-guide-to-learning-angularjs-in-one-day/