ANGULAR2 Series Tutorials (vii) service

Source: Internet
Author: User
Tags export class

Today we are going to talk about the concept of ng2 service, like NG1, the service is usually used to send HTTP requests, but in fact you can encapsulate any of the methods you want to encapsulate, and sometimes the communication between the controller depends on the service to complete, let us see quickly!

Example

Example is the official example, load a list of heroes, click Show Details. I put it directly in our upgraded gear.

Source

Injectable

How do you write services in NG2? Very simple, you just need to decorate a injectable on your class.

Src/app/hero.service.ts (partial code)

@Injectable () Export class Heroservice {  getheroes () {    return  promise.resolve (Heroes);  }   // See the ' Take It slow ' appendix   getheroesslowly () {    returnnew promise       // 2 seconds     );  }}

What do we do with the above code?

    1. Wrote a class that uses injectable decorations
    2. Two member functions were written
    3. One returns a promise, directly resolve data
    4. The other also returns a promise, but after two seconds the resolve data

Some students will ask: where is the data of resolve? What is promise? We continue to explain.

Promise

If you have played ng1, you must be not unfamiliar with promise, because we often write resolve in the route, here can accept a promise object. And the $q in Ng1 .defer () and so on.

But promise is not a NG1 patent, you can use promise in any of your JavaScript programs because promise objects are already available in ES6. You can see how it is used, here I briefly describe:

    1. To construct a promise, just add a parameter to it, this parameter is a function, this function can accept two parameters: Resolve, Reject
    2. Using the Promise object, the most common method is then (), which takes a parameter that is the value of resolve. Besides then () there are catch () and so on

So why do we use promise? Mainly to solve the problem of callback hell. Because of the promise, you don't have to write deep callbacks, it's like a synchronous notation.

This is part of my code for a NG1 project, with promise then () to fix the callback to hell.

Auth. $createUser ({email:email, password:pass}). Then (function() {                            //authenticate so we had permission to write to Firebase                            returnAuth. $authWithPassword ({email:email, password:pass}); }). Then (function(user) {//Create a user profile in our data store                            varref = Wdutil.ref (' users ', User.uid); returnWdutil.handler (function(CB) {Ref.set ({email:email, Name: $scope. Name||firstpartofemail (email)}, CB);                        }); }). Then (function(/*User*/) {$scope. Wait.show=false; //redirect to the Account page$location. Path ('/account '); }, function(Err) {$scope. Wait.show=false; $scope. Alerts.push ({type:' Danger ', Msg:wdutil.errMessage (ERR)}); });
Interface

In the process of writing this service we used the concept of interface, which belongs to the category of TS, and we usually declare the type in the interface, a bit like the proptypesin react:

Src/app/hero.ts

Export interface Hero {  id:number;  name:string;}

Then we used this interface in our service:

Src/app/hero.service.ts (partial code)

Import {Hero} from './hero ';

Src/app/hero.service.ts (partial code)

return New promise      //  2 seconds    );

For the first time, we have used this interface several times in our components:

Src/app/app.component.ts

Heroes:hero[];  Selectedhero:hero;

Src/app/hero-detail.component.ts

Export class Herodetailcomponent {  Hero:hero;}

So far, our service is even written!

Using the service

Let's test the service we've written in the component:

Src/app/app.component.ts (partial code)

Import {Heroservice} from './hero.service ';

Src/app/app.component.ts (partial code)

Providers: [Heroservice]

Src/app/app.component.ts (partial code)

Constructor (Private _heroservice:heroservice) {}  getheroes () {    this. Heroes = Heroes);  }

The above code we did these things:

    1. Use the module system to import this service class
    2. Inject this service into the component
    3. Assign the service to a private variable in the constructor _heroservice
    4. Then you can use this service object in your class This._heroservice

The Getheroes () here returns a promise, so we can use then to deal with what happens next.

Tutorial source code and directory

If you feel that this blog tutorial has helped you, take a star!

Https://github.com/lewis617/angular2-tutorial

ANGULAR2 Series Tutorials (vii) service

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.