Creating a new Angular Service

Any code that touches outside of the boundaries of a component should exist in a service; this includes inter-component communication, unless there's a parent-child relationship, and API calls of any kind and any code that cache or retrieve data from a cookie or the browser's localStorage. This is a critical architectural pattern that keeps your application maintainable in the long term. I expand upon this idea in my DevPro MVVM article at http://bit.ly/MVVMvsMVC.

To create an Angular service, do this:

  1. In the terminal, execute npx ng g s weather --flat false
  2. Observe the new weather folder created:
src/app...└── weather   ├── weather.service.spec.ts   └── weather.service.ts

A generated service has two parts:

Get Angular 6 for Enterprise-Ready Web Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.