質問

I'm getting started in AngularJS and I see people is talking about a "service() vs factory()" dilema but I cannot find any documentation about the first one.

So, should we force ourself to use factory()? or it's just like an alias?

Thanks in advance

役に立ちましたか?

解決

Some sentences I wish I had read when I started using angular.

  • A provider is a function that gets newed. And can be injected into a config block in that state.

    When its time to be used (ie. injected elsewhere) $get is called and the return value from that is your provider.

  • A service is a function that gets newed and thats your service.

  • A factory is a function that gets newed and executed. Its return value is your factory.

The three different terms are just to differentiate the method in which they're created.

Some good uses for each:

  • provider: As a configuration for an angular library or api service
  • service: a 'class like' object. Maybe for storing shared application data
  • factory: a data retrieval object that handles getting and saving of data.. maybe into your service.

他のヒント

Pass a class or function constructor to the service. Angular will do the equivalent of calling "new" on it.

Pass a function that returns the object you want to the factory. Angular will take what you pass, call it, and use the return value.

For example, factory:

function(dep1, dep2) {
   return {
       total: dep1.x + dep2.x 
   };
}

Service:

function MyClass(dep1, dep2) {
   this.total = dep1.x + dep2.x 
}

Factory is usually fine unless you are using a language like TypeScript or CoffeeScript that directs you more to classes.

The Provider is simply a service that can be configured once. In other words, if you have something that needs to be set up when you are initializing modules in the config block, use a provider. That allows you to tweak configuration before it is stored as an object to be used.

Let me know if that answers your question!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top