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?
Asked
Active
Viewed 248 times
0
-
https://angular.io/guide/styleguide#talk-to-the-server-through-a-service – JB Nizet Dec 17 '17 at 20:34
-
1For sure it's much cleaner to create a service and place API requests there. One service for each API controller. This will prevent you from duplicating same calls to the API and will keep you service as single responsibility. This will lead to cleaner code and it will be easier to maintain. You can also have some base API service with `apiBaseUrl`, etc. – Vitalii Chmovzh Dec 17 '17 at 21:03
-
definitely agree with you ... any possible site or book i could refer to to follow your guidelines? Many thanks in advance. – Metrophobe Dec 17 '17 at 21:50
-
@Metrophobe again, https://angular.io/guide/styleguide#talk-to-the-server-through-a-service. It's the official angular style guide. What else do you need? – JB Nizet Dec 18 '17 at 08:08
-
it is ok thanks will look into the details of it :) thanks again – Metrophobe Dec 19 '17 at 17:52
1 Answers
1
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

Evonet
- 3,600
- 4
- 37
- 83