프로그래밍/JavaScript

AngularJS - Service,Factory 그리고 Provider의 차이

Terry Cho 2014. 1. 17. 11:54

결과적으로 모두 Service를 정의하는 방법의 차이 - 코딩 스타일의 차이? (그렇다면 왜 만들어 놨을까?)


What is service,factory and provider


Difference between service and factory

http://blog.manishchhabra.com/2013/09/angularjs-service-vs-factory-with-example/


서비스를 생성하는 방법이 여러가지가 있는데 (클래스를 객체화 시키는 것 처럼)

Service를 가지고 직접 생성하는 방법이 있고,

아니면 Factory를 생성한후, Factory에서 instance를 받는 방법이 있고

아니면 Constructor에서, 받아서 생성하는 방법이 있고

또는 Provider를 사용하는 방법이 있다.


개념은 잡았는데, 구현 하라면 못하겄네.


아래는 service를 가지고 생성하는 방법

Service를 이용해서 생성하는 방법은 Common 서비스나 재사용 가능한 서비스를 정의 하는데 유리함



var app = angular.module('myApp', []);

     

// Service definition

app.service('testService', function(){

    this.sayHello= function(text){

        return "Service says \"Hello " + text + "\"";

    };        

});

 

// AngularJS Controller that uses the service

function HelloCtrl($scope, testService)

{

    $scope.fromService = testService.sayHello("World");

}


아래는 factory를 가지고 생성하는 방법

이건 class를 리턴해야 하는 경우에 유리함. (별 차이 없어 보이는데?)


var app = angular.module('myApp', []);

 

// Factory

app.factory('testFactory', function(){

    return {

        sayHello: function(text){

            return "Factory says \"Hello " + text + "\"";

        }  

    }               

});

 

// AngularJS Controller that uses the factory

function HelloCtrl($scope, testFactory)

{

    $scope.fromFactory = testFactory.sayHello("World");

}



그리드형