Angular by Shyam Seshadri

Angular by Shyam Seshadri

Author:Shyam Seshadri
Language: eng
Format: epub
Publisher: O'Reilly Media
Published: 2018-06-21T16:00:00+00:00


ng g service services/stock

This will generate two files, a skeleton stock-service.ts and a dummy test for it in stock-service.spec.ts. We will ignore the latter for now but will return to it in Chapter 10, as part of our discussion of unit testing of services. The generated skeleton in src/app/service/stock.service.ts should look something like this:

import { Injectable } from '@angular/core'; @Injectable() export class StockService { constructor() { } }

The skeleton is literally just an empty shell class, with one decorator of note, which is Injectable. The Injectable decorator has no current value for us, but is a recommended decorator whenever you are working with services, as it is a hint to the Angular dependency injection system that the service you are working on might have other dependencies. With the Injectable decorator, Angular will take care of injecting them into our service.

We will leave the decorator untouched, keeping with the best practices. And pretty soon, as early as the next chapter, we will need it anyway.

Now, let’s get to the crux of the work, which is the data that the StockService is to provide. This is where services really shine. Components generally will defer and ask a service for data (or a section of the data). It is up to the service to decide how and where to fetch the data from, whether it is from a web service via HTTP calls, a local storage or cache, or even return mock data, as we will in just a bit. Later, if we want to change the source, we can do it in one place without touching any of the components, as long as our API signature remains the same.

Let’s define our StockService to continue returning mock data. We will edit the src/app/services/stock.service.ts file as follows:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.