What is the service in ANGLAR2?
If there is a piece of code in the project that many components use, the best way is to make it a service.
A service is a mechanism for sharing functionality in a component, and when we use tags to combine multiple components together we need to manipulate some data or we need to do some arithmetic, we need to do a service, the service can help us to introduce external data. So how do you create a service?
Create a service
Create a simple service
Import {injectable} from ' Angular2/core ';
Import {planets} from './planets-data ';
@Injectable ()
Export Class Planetservice {
Getplanets () {
Return Promise.resolve (planets);
}
}
First, you need a injectable directive that tells other referenced components that the service is available for injection.
Then define a method to return the data.
Service invocation
Service invocation is also simple
Import {Component} from "Angular2/core";
Import {Planetservice} from "./planet.service"; 1
Import {planetcomponent} from "./planet.component";
Import {Planet} from "./planet";
@Component ({
Selector: "My-app",
Templateurl: "App/planet-list.component.html",
directives: [Planetcomponent],
Providers:[planetservice],//2
Styles:['
body{
padding:0;
margin:0;
Font-family:roboto,arial,sans-serif;
Font-size:16px
}
. title {
Color: #018EFA;
}
. clicked{
Background-color: #9C00FE;
Color:white;
}
. labels{
Background-color:black;
Color:white;
}
`]
})
Export Class planetlistcomponent{
Public planets:planet[];
Public selectedplanet = {};
Public Onnameclick (planet) {
This.selectedplanet = Planet;
}
Constructor (private _planetservice:planetservice) {//3
This.getplanets ();
}
Make a call to our planet service
Getplanets () {//4
This._planetservice.getplanets (). Then ((planets:planet[]) =>this.planets = planets);
}
}
1. Introduction Service (Import)
2, using providers to inject services
3. Create an example of a service
Invoking a service using promise
ANGULARJS2 Study Notes (iii) services