angular.service vs angular.factory

后端 未结 9 2149
走了就别回头了
走了就别回头了 2020-11-22 02:50

I have seen both angular.factory() and angular.service() used to declare services; however, I cannot find angular.service anywhere in official documentation.

9条回答
  •  梦谈多话
    2020-11-22 03:03

    Here are the primary differences:

    Services

    Syntax: module.service( 'serviceName', function );

    Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service.

    Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending ( ) to the injected function reference. Could also be run with injectedArg.call( this ) or similar.

    Factories

    Syntax: module.factory( 'factoryName', function );

    Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

    Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.

    Here is example using services and factory. Read more about AngularJS Service vs Factory.

    You can also check the AngularJS documentation and similar question on stackoverflow confused about service vs factory.

提交回复
热议问题