When creating service method what's the difference between module.service and module.factory

后端 未结 2 1804
执念已碎
执念已碎 2020-12-12 21:34

I don\'t know what is the best practice and what I should use.

What is the difference between below two methods?

module.service(..);
<
2条回答
  •  囚心锁ツ
    2020-12-12 22:06

    Consider the following service.

    angular.module("myModule", [])
    .service("thingCountingService", function() {
        var thingCount = 0;
        this.countThing = function() { thingCount++; }
        this.getNumThings = function() { return thingCount; }
    });
    

    If you had an app, in which a variety of controllers, views, etc, all want to contribute to one general count of things, the above service works.

    But what if each app wants to keep its own tally of things?

    In that case, a singleton service would not work since it can only keep track of all of them. However, a factory lets you create a new service every time you want to start a new counter.

    angular.module("myModule", [])
    .factory("thingCountingServiceFactory", function() {
        var thingCount = 0;
        this.countThing = function() { thingCount++; }
        this.getNumThings = function() { return thingCount; }
    });
    

    With the above factory, you can call new thingCountingServiceFactory() at any time and get a new thingCountingService set to 0

提交回复
热议问题