Confused about Service vs Factory

后端 未结 20 2879
轻奢々
轻奢々 2020-11-22 08:49

As I understand it, when inside a factory I return an object that gets injected into a controller. When inside a service I am dealing with the object using this

20条回答
  •  面向向阳花
    2020-11-22 09:17

    This would be the best and short answer for understanding Service Vs Factory Vs Provider

    Source: https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/HuZsOsMvKv4J

    Here what ben says with a demo http://jsbin.com/ohamub/1/edit?html,output

    "There are comments in the code illustrating the primary differences but I will expand on them a bit here. As a note, I am just getting my head around this so if I say anything that is wrong please let me know.

    Services

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

    Result: When declaring serviceName as an injectable argument you will be provided the actual function reference 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 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.

    Providers

    Syntax: module.provider( 'providerName', function );

    Result: When declaring providerName as an injectable argument you will be provided the value that is returned by invoking the $get method of the function reference passed to module.provider.

    Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances but that requires some sort of configuration before being injected. Perhaps useful for classes that are reusable across projects? Still kind of hazy on this one." Ben

提交回复
热议问题