By Gary simon - Apr 19, 2017
When developing an Angular app, you will most likely run into a scenario in which you need to use the same code across multiple components. You may even need to share data between components, or you may need to fetch data from a database of some sort.
It's these times when creating an Angular service makes sense. An angular service is simply a function that allows you to access its' defined properties and methods. It also helps keep your coding organized.
So, let's get started.
Be sure to subscribe to the official Coursetro youtube channel for more awesome videos.
This tutorial is a part of our Free Angular 4 Course, and we've already established a project that was generated with the Angular CLI. So, I'm going to assume you're following along with the course. If not, use the the Angular CLI to generate a project and then you can hop right in.
The Angular CLI allows you to quickly generate a service. It takes care of some of the manual labor involved with service creation.
To create a service, at the console in the project folder type:
> ng g service data
Upon running this, your output may look something like:
installing service
create src\app\data.service.spec.ts
create src\app\data.service.ts
WARNING Service is generated but not provided, it must be provided to be used
The warning simply means that we have to add it to the providers property of the NgModule decorator in src/app/app.module.ts, so let's do that:
// Other imports removed
import { DataService } from './data.service';
@NgModule({
// Other properties removed
providers: [DataService],
})
Great. Save it and let's move on.
Now that we have created a service, let's take a look at what the Angular CLI created:
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
constructor() { }
}
It looks fairly similar to a component, except that it's importing an Injectable as opposed to a Component. The Injectable decorator emits metadata associated with this service, which lets Angular know if it needs to inject other dependencies into this service.
We will not be injecting any dependencies into our simple example service here, but it is recommended to leave the Injectable decorator for future-proofing and ensuring consistency. But you could get rid of lines 1 and 3 and our service would still work.
So, ordinarily, at this point, you may connect to a database to return results, but to keep things simple here, let's hardcode our own array and create a simple method:
export class DataService {
constructor() { }
cars = [
'Ford','Chevrolet','Buick'
];
myData() {
return 'This is my data, man!';
}
}
As you can see, we're just creating a simple array and a method called myData() that returns a string.
So, how do we access these properties and methods from another component? Simple!
The first step requires importing the service at the top of the component. So, in app.component.ts:
import { DataService } from './data.service';
Next, within the constructor, we have to import it through dependency injection:
export class AppComponent {
constructor(private dataService:DataService) {
}
}
Now we can use dataService to access its's associated properties and methods.
Underneath the constructor() { }, let's add the ngOnInit() lifecycle hook, which runs when the component loads:
someProperty:string = '';
ngOnInit() {
console.log(this.dataService.cars);
this.someProperty = this.dataService.myData();
}
First, we're console logging the cars array, and then we're binding someProperty to the myData method that we defined in the service.
In the template property of the @Component() decorator, add:
@Component({
// Other properties removed
template: `
<p>{{ someProperty }}</p>
`
})
Now, run ng serve at the console in the project folder, and you should see in your console the array of cars that we defined, along with the string of, "This is my data, man!" that we returned in the myData() method.
So, this in a nutshell are how Angular services work. You create services that are specific to a single purpose, which can be reused across multiple components in your Angular app.