Submodule 20.3: Services and Dependency Injection - Practice

Site: ΕΛ/ΛΑΚ Moodle
Course: Study / Web Design and Web Development
Book: Submodule 20.3: Services and Dependency Injection - Practice
Printed by: Guest user
Date: Thursday, 21 November 2024, 5:36 PM

Introduction

In this submodule, you will create a new Angular service and inject it into your application.
You will then make use of the service in the components. You will:

  • Implement a service and inject into your application
  • Make use of the service in a component

The above will not affect how the page is displayed on the browser.

Adding a Service

Open the angularChocoYourname  angular-sub-folder in your Visual Editor code and create a folder named services in the src/app folder.


Open your Terminal and move to the angularChocoYourname  angular-sub-folder.

To add a service to your application using Angular CLI, type the following at the prompt:

ng generate service services/dish

This will create two new files in the services folder named dish.service.spec.ts and dish.service.ts.

  • This first one is used for testing our angular service.
  • The second one is where we will create our dish service and then inject that into our app module and make use of it in our menu component. 

Note

The very first statement there says import injectable from @angular/core.

This statement allows us to define the decorator @Injectable() . Any class to which we apply this decorator becomes injectable. 

By using this injectable decorator to theDishService, we are making this object now injectable within our application. So this is what enables the dependency injection to be used within our application. 

Updating the Service

Open dish.service.ts and update its contents as shown below:

import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { DISHES } from '../shared/dishes';

@Injectable()
export class DishService {

constructor() { }

getDishes(): Dish[] {
return DISHES;
}
}

Notice

  • the imports of the Dish class and the DISHES constant from the shared folder. So once we've imported these two, our service can be configured to provide the value for us.
  • the new method called getDishes. This method will return the DISHES array which has been defined in the dishes.ts. With this, our Dish service is now configured to supply that DISHES JavaScript object array to any other part of our application that requires it.

Updating the app.module

Then add the service to the app.module.ts file as follows:

. . .
import { DishService } from './services/dish.service';
@NgModule({
. . .
providers: [DishService],
. . .

Notice

  • the import of the DishService from ./services/dish.service here.
  • the declaration of this DishService as a provider.

So, if you are going to the @NgModule decorator, you see this third property here called provider. In the @NgModule we have declarations, imports and providers.
So whenever you have a service that you want to make available for all the components that are part of this module, you will specify that as a provider within the module.
So with this, my DishService now becomes available for the rest of the application. How does this happen? The Angular's dependency injector will look at this information that we have declared here and then decide that it needs to create a DishService and inject it wherever it is required.

Using the Service

Update the menu.component.ts file to make use of the service as follows:

. . .
import { DishService } from '../services/dish.service';
. . .
export class MenuComponent implements OnInit {
  dishes: Dish[];
  selectedDish: Dish;
  constructor(private dishService: DishService) { }
  ngOnInit() {
    this.dishes = this.dishService.getDishes();
  }
  . . .
}

Notice

  • the import of the DishService from ./services/dish.service. Since we do this import, we no longer need the import { DISHES } from '../shared/dishes';.
     This means that we also can't use the dishes = DISHES; assignment. 
  • constructor(private dishService: DishService) { }.
    With this, we make the service that we have imported available for our components to make use of it. Since we have injected the DishService in the app module, Angular uses the constructor to create a replicate of the DishService , which in this case we have named it dishService<, this is just a name. 
  • dishes: Dish[];. Since we no longer have the DISHES constant, we need to find an alternative way to fetch the information ...
    • ngOnInit() { ... }. This is a life-cycle method. In the
      export class MenuComponent implements OnInit { ... } 
      we see that we have the implementation of the OnInit. 
      So, this is the place this.dishes = this.dishService.getDishes();where you fetch the information. Every time that the user "asks" for this service, angular creates an instant of that DishService and fetch the information needed.

The results

With the previous code configured, open your Terminal, go to the angularChocoYourname  angular-sub-folder and run ng serve to run your application in development mode. In your browser navigate to the URL localhost:4200 

Check that your application is still working correctly in the browser!!

Do a Git commit with the message "Angular Service".