Metrophobe
Metrophobe

Reputation: 93

Angular HttpClient and Services

Ok so a quick question. I am seeing a lot of implementations whereby developers implement an api request in the component directly since HttpClient is injectable. Is this the way to go or is it cleaner (from a purist point of view) to have a proper service and have all the HttpClient requests in there? Any reputable source i could refer to for a complete example involving HttpClient + Express + Services?

Upvotes: 0

Views: 293

Answers (1)

Evonet
Evonet

Reputation: 3640

Definately use services so that you have a central place for your API requests.

I typically have one service for each type of api, ie, /products, /orders etc. I find that (as an example) components from all around my application may call endpoints within /products, so separating into services makes the code much cleaner.

I place these services in a CoreModule https://angular.io/guide/ngmodule-faq#coremodule.

Here is an example of how to use api calls from services, instead of directly from components. https://www.concretepage.com/angular-2/angular-httpclient-get-example

Upvotes: 1

Related Questions