How to use a single-case model and angular services

Source: Internet
Author: User
Tags instance method

There are some classes in real life that have such characteristics:

A . These classes can have only one instance;

B . these can be automatically instantiated;

C . This class is visible to the entire system, which must provide this instance to the entire system.

Consider a specific example of a singleton pattern: teachers and students in the classroom are required to write on the blackboard, but in general, there should be only one blackboard in the classroom, which is a common drop for teachers and students. It's time to find a way to make sure that the blackboard is a shared, unique object. The singleton pattern is an already formed pattern to solve this kind of problem.

Angularbrings many types of services. Each will have its own different usage scenarios. We will explain this in this section.

The first thing we have to keep in mind is that all services are Singleton ( Singleton) , which is what we want to expect.

Let me start today's Services Tour :

Constant

Example:

App.constant (' Fooconfig ', {config1:true,config2: "Default Config2"});

Constant is a useful thing, and we often use it for configuration information such as directive. So when you want to create a directive, and you want to be able to do some configuration information while giving some default configuration, constant is a good choice.

Constant can be translated as constants, because the value we set is not changed. It can accept the underlying type and object objects.

Value

Example:

App.value (' Fooconfig ', {config1:true,config2: "Default config2 but it can changes"});

The value is similar to the constant above, except that it can be changed after the assignment. It is also commonly used in directive configuration information. Value Service will only retain values, and we will not evaluate it in the service.

Factory

Example:

App.factory (' foo ', function () {var thisisprivate = "Private"; function Getprivate () {return thisisprivate;} return {variable: "This was public", Getprivate:getprivate};});

Factory is our most commonly used service. It is easy to be understood.

Factory will return an object , and there is no limit to how you can create the object angular . In the example I chose my favorite mode revealing module pattern, you can choose the other way you want.

As I said before, all services are singleton , so when we modify foo.variable , it affects other places of use.

Service

Example:

App.service (' foo ', function () {var thisisprivate = "Private"; this.variable = "This was public"; this.getprivate = function ( ) {return thisisprivate;};});

Service service and factory work the same way, except that the service receives a constructor, and when the service is first used , angular will be new Foo () To initialize the object. The same object is returned at a later time.

In fact, the following is a factory equivalent notation:

App.factory (' Foo2 ', function () {return new Foobar ();}); function Foobar () {var thisisprivate = "Private"; this.variable = "This was public"; this.getprivate = function () {return thi Sisprivate;};}

Foobar is a class ( Class) in factory We manually initialize it, returning it. Same as Service Foobar class is initialized only the first time, and later returns the same object.

If we already have a class, then I can use it directly:

App.service (' Foo3 ', Foobar);

Provider

Provider is a final advanced option in angular, the last example in the example factory with Provider will be as follows:

App.provider (' foo ', function () {return {$get: function () {var thisisprivate = "Private"; function Getprivate () {return thi Sisprivate;} return {variable: "This was public", getprivate:getprivate};};});

Provider has a $get function, and its return value will be injected into other application components. So we injected Foo into the controller, and we injected the $get function.

Why do we still need provider, factory implementation is not simpler? This is because we are able to configure provider in the Config function. As shown below:

App.provider (' foo ', function () {var thisisprivate = "Private"; return {setprivate:function (newval) {thisisprivate = newval;}, $get: function () {function getprivate () {return thisisprivate;} return {variable: "This was public", getprivate:getprivate};};}); App. Config (function (fooprovider) {fooprovider.setprivate (' New value from config ');});

Here we move the thisisprivate out of the $get function, and we create a setprivate function that enables it to modify the thisisprivate variable in the config function . Why do we need to do this? is it okay to add a setter to the factory ? This is a different intention.

We want to inject an object , but we also want to provide a way to configure it. For example: a service that wraps a JSONP resource resource, we want to be able to configure the resource from that URL , and we'll have a three-party consumer like Restangular Allow us to configure to achieve our purpose.

Note that in the config function we need to replace name with Nameprovider, but consumers only need to use name.

You can see that some services have been configured in our application,such as $routeprovider, $locationProvider, configuring our Routes and Html5model adaptation.

Additional benefits:Welfare 1: Decorator decorator

If you feel that the Foo service I gave you lacks the greet method you need , do you need to change the API? No, you can decorate it in a better way:

App. Config (function ($provide) {$provide. Decorator (' foo ', function ($delegate) {$delegate. greet = function () {return] Hello, I am a new function of ' foo ';}; return $delegate;});

     Previous example $provide Service We can use $provide to decorate) There is a decorator Name represents our original Service instance.

Here we can decorate our service. In this example we have added a greet function on the original service instance , returning the modified service. When we consume this service , it will contain a greet function that you can see in the try it below .

For using a service from a third party,when we expect to do some expansion of its interface, we do not need to copy its code to our project to modify it, we can manually easily use the decorator to achieve what we want.

Note: The constants mentioned above are constant not to be decorated.

Benefit 2: Create non-singleton objects

As we know all the service is singleton, but we can still create a non-singleton object. Before we go any further, we must realize that most scenarios we would expect to be a singleton service, and we will not change that mechanism. In other words, in a few scenes we need to generate a new object object every time . As follows:

Our classfunction person (JSON) {angular.extend (this, JSON);} Person.prototype = {Update:function () {//update it (with real code:P) this.name = "Dave"; this.country = "Canada";}}; Person.getbyid = function (ID) {//do something to fetch a person by the Idreturn new person ({name: "Jesus", Country: "Spa In "});};/ /Our Factoryapp.factory (' Personservice ', function () {return {getById:Person.getById};});

Here we create a person object, which has several JSON objects to initialize the object. Next we create a function in prototype ( which can be understood as an instance method from object-oriented language), where we add a method directly to the person class (which can be understood as a class method, a static method).

So we have a class method that creates a new person object based on the ID we provide , and each instance can update itself. Next we just need to create a service to consume it.

At any time we call Personservice.getbyid, we will create a new person object, so you can use a new person object in a different controller , Even though the factory is a singleton, it produces a new object that returns.

Welfare 3: Coffeescript

Coffeescrip is able to gracefully handle the service, providing an elegant way to create class. Here is an example of the benefit 2 with Coffeescript changed:

App.controller ' Mainctrl ', ($scope, Personservice), $scope. Aperson = Personservice.getbyid (1) App.controller ' Secondctrl ', ($scope, Personservice) $scope. Aperson = Personservice.getbyid (2) $scope. Updateit = ()->$ Scope.aPerson.update () class Personconstructor: (JSON)->angular.extend @, Jsonupdate: () @name = "Dave" @country = "Canada" @getById: (ID)->new personname: "Jesus" Country: "Spain" App.factory ' Personservice ', ()->{getbyid: Person.getbyid}

Translator Note: I have been thinking about why you need to try Coffeescript in your project. Coffeescript not only graceful grammar, if this is the case, at best it is just some dispensable grammatical sugar, we think it is more important for us to write JavaScript has brought some good practice, bypassing the JavaScript " Pit. " but also have to consider the project members of the cost of learning, if your project members have a lot of functional programming experience, JavaScript ability is good, you can completely try. Note: Writing Coffeescript does not mean that you no longer need JavaScript to learn.

Summary:

The service is Angularjs Another very cool features. There are many ways to create a service, and we need to choose the right way to implement it based on our application scenario. The Translator notes: This is like the design pattern that we often hang on the lips, it is important to use the correct pattern for the correct scene.

How to use a single-case model and angular services

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.