DEV Community

Julie Gladden
Julie Gladden

Posted on

What are services in Angular? And how in the world do I use them?

Hi folks,

Let's talk about services today. These guys are extremely useful for having code that is streamlined, reusable, and readable.

You might have services for different things, for example:

  • A service that holds all of your API calls.
  • A service that holds a bunch of constants, like URLs.
  • A service that holds a variable or observable, that other components can subscribe to read and use that data.
  • Using Rxjs Behavior Subject, you can even update and subscribe to the same variable in a service through many different components.

For initial setup, I would create a folder called 'services'.
Then, in your terminal pointed to that folder, you can add the command:

ng g s service-name

Service-name can be whatever you want it to be. Like, 'authentication' or 'api-calls'. It will end up being called 'service-name.service', so don't name it something like 'authentication-service', or else you'll end up with 'authentication-service.service'.

For today's purpose, let's have a service that has a constant and an API call.

Example:

export class ApiCallService { 

constructor(private http: HttpClient) {}

const url = www.hereisadomainname.com


getDataFromDatabase() {
return this.http.get(this.url + '/data')
}

}
Enter fullscreen mode Exit fullscreen mode

Now, you can use these in whatever component you want.

Ex:

export class YourComponent {
myVariable; 

//The name after private can be whatever you want, you are just assigning the service's name here.
constructor(private service: ApiCallService) {}

// You can see here, that 'service' is targeting our ApiCallService, then we can pull any variable or function directly from the service for our use!
getData() {
this.service.getDataFromDatabase().subscribe(data => console.log(data)
}

ngOnInit() {
//this is going to print the url you have in your service. You could have other data stored, like an array or object. Then you can assign the value to a variable in your component.

console.log(this.service.url)
//or
this.myVariable = this.service.url
}

}
Enter fullscreen mode Exit fullscreen mode

Hopefully you can see the usefulness of a service, especially when you have a lot of code that needs to be reused in many different places.

Please leave a comment if you have any Angular tutorial requests! I'd love to see what you want to know. :)

Thanks for reading,
Julie

Top comments (0)