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?
- Wrote a class that uses injectable decorations
- Two member functions were written
- One returns a promise, directly resolve data
- 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:
- To construct a promise, just add a parameter to it, this parameter is a function, this function can accept two parameters: Resolve, Reject
- 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:
- Use the module system to import this service class
- Inject this service into the component
- Assign the service to a private variable in the constructor _heroservice
- 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