IT story

AngularJS : 공장이란?

hot-time 2020. 8. 19. 20:00
반응형

AngularJS : 공장이란?


저는 많은 작업을 해왔고 Angular.js전반적으로 흥미롭고 강력한 프레임 워크라고 생각합니다.

서비스 대 공장 대 공급자 대 가치에 대해 많은 논의가 있었음을 알고 있지만 여전히 a Factory무엇인지 꽤 혼란 스럽습니다 .

Factory는 다른 StackOverflow 토론에서 다음과 같이 정의되었습니다.

공장

구문 : module.factory( 'factoryName', function );결과 : factoryName을 주입 가능한 인수로 선언하면 module.factory에 전달 된 함수 참조를 호출하여 반환되는 값이 제공됩니다.

이 설명은 이해하기가 매우 어렵고 공장이 무엇인지에 대한 이해를 높이 지 않습니다.

a Factory정확히 무엇 Service이며 Provider, 또는 기타 대신 사용해야하는 이유 에 대해 공유 할 수있는 설명이나 실제 사례가 있습니까?

최신 정보

A service 모든 객체에 대한 참조보유 합니다 .

A factory 모든 객체 를 반환 하는 함수 입니다.

A provider 모든 함수 를 반환하는 함수입니다.

- -


내가 이해하는 바에 따르면 그들은 모두 거의 동일합니다. 주요 차이점은 복잡성입니다. 공급자는 런타임에 구성 할 수 있고 공장은 좀 더 강력하며 서비스는 가장 간단한 형태입니다.

이 질문을 확인하십시오 AngularJS : 서비스 대 공급자 대 공장

또한이 요지 는 미묘한 차이를 이해하는 데 도움 될 수 있습니다.

출처 : https://groups.google.com/forum/#!topic/angular/hVrkvaHGOfc

jsFiddle : http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/

저자 : Pawel Kozlowski

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

//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
    this.sayHello = function() {
        return "Hello, World!";
    };
});

//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "Hello, World!";
        }
    };
});

//provider style, full blown, configurable version     
myApp.provider('helloWorld', function() {
    // In the provider function, you cannot inject any
    // service or factory. This can only be done at the
    // "$get" method.

    this.name = 'Default';

    this.$get = function() {
        var name = this.name;
        return {
            sayHello: function() {
                return "Hello, " + name + "!";
            }
        };
    };

    this.setName = function(name) {
        this.name = name;
    };
});

//hey, we can configure a provider!            
myApp.config(function(helloWorldProvider){
    helloWorldProvider.setName('World');
});


function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {

    $scope.hellos = [
        helloWorld.sayHello(),
        helloWorldFromFactory.sayHello(),
        helloWorldFromService.sayHello()];
}​

한 가지 큰 차이점은 공장에서 사용자 지정 코드를 실행할 수 있다는 것입니다. 그러나 서비스에서는 객체 생성 만 발생합니다.

myJs.factory('Factory', function() {

    //Write custom code here

    return {
            Hello: function() {
            return "Hello, World!"
        }
    };
});

이 주제에 대한 나의 2 센트. 저는 매우 초보이며 Angular JS를 이해하는 데 관심이 많았습니다. 이것은 저를 많이 혼란스럽게 만든 것 중 하나 였기 때문에 다소 자세히 연구했습니다. 나는 인터뷰를 위해 메모를 해왔고 이것은 다른 사람들에게 유용 할 수 있습니다.

  • 서비스와 공장은 다른 방식으로 같은 일을합니다.
  • 둘 다 주사제입니다
  • 대부분의 경우 팩토리 구문을 사용합니다.
  • 이해하기 쉬움
  • nowadays with es6 "service" is done since it converts to es6 classes better
  • its essentially abstracting away business logic from the controller
  • if you use biz logic with controllers then you can only use with controllers
  • controller is for putting data on scope not processing lengthy biz logic
  • so what happens in above scenario is that complex biz logic is tied up into controllers. Not for processing data. So put bits and pieces of it into services or factory. So your code is lean and modular.
  • services are singletons

Services are mostly objects in which you describe the constructor class of the object. Somewhere deep within the framework, the Object.create() function is called and then you can use a service by calling its object and methods using a controller. Factory, on the other hand, doesn't create an object by default and hence requires you to return the entire object location once you're done defining all the attributes and methods.

참고URL : https://stackoverflow.com/questions/16596569/angularjs-what-is-a-factory

반응형