官术网_书友最值得收藏!

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:

  • weather.service.spec.ts contains Jasmine-based unit tests that you can extend to test your service functionality.
  • weather.service.ts contains the @Injectable decorator above the class definition, which makes it possible to inject this service into other components, leveraging Angular's provider system. This will ensure that our service will be a singleton, meaning only instantiated once, no matter how many times it is injected elsewhere.

The service is generated, but it's not automatically provided. To do this, follow these steps:

  1. Open app.module.ts
  2. Type in WeatherService inside the providers array
  3. Use the auto-fixer to import the class for you:
src/app/app.module.ts
...
import { WeatherService } from './weather/weather.service'
...
@NgModule({
  ...
  providers: [WeatherService],
  ...

If you installed the recommended extension TypeScript Hero, the import statement will be automatically added for you. You won't have to use the auto-fixer to do it. Going forward, I will not call out the need to import modules.

主站蜘蛛池模板: 湟源县| 康保县| 孝义市| 慈溪市| 呼伦贝尔市| 白玉县| 九龙城区| 梁平县| 厦门市| 怀化市| 始兴县| 信丰县| 六枝特区| 弥勒县| 莱芜市| 中西区| 海口市| 平谷区| 开阳县| 扎鲁特旗| 新竹县| 佛山市| 昌宁县| 海淀区| 宜昌市| 个旧市| 新邵县| 中卫市| 钟祥市| 花莲市| 岗巴县| 旬阳县| 图片| 三河市| 桂东县| 淳安县| 阿尔山市| 伊金霍洛旗| 新津县| 博白县| 庆城县|