Angular 5 Services

Previously:

 

Now in this part we will be discussing about Angular 5 Services:

  • Let us create a service say “data”
    • $ ng g service data
  • Let us check the service file at /src/app/data.service.ts
    • import { Injectable } from ‘@angular/core’;@Injectable()export class DataService {

          constructor() { }

      }

  • Now from above we can see a service looks like a Component but with @injectable() which means it can be imported into any Component
  • Let us update the service code as:
    • import { Injectable } from ‘@angular/core’;@Injectable()export class DataService {

          private itemName= ‘Apple’;    //Create itemName

         constructor() { }

          getItemName() {
              return this.itemName;
          }
      }

Let us import the service now

  • Add the service to /src/app/app.module.ts:
    • import { DataService } from ‘./data.service’;

      providers: [
           DataService
      ],

  • Import service to component  /src/app/home/home.component.html
    • import { Component, OnInit } from ‘@angular/core’;
      import { DataService } from ‘../data.service’; //Import the Service
      @Component({
          selector: ‘app-home’,
          templateUrl: ‘./home.component.html’,
          styleUrls: [‘./home.component.scss’]
      })
      export class HomeComponent implements OnInit {
          itemName = “Apple”;
          buttonText = “Change Name”;
          constructor(private _data: DataService) { }
          ngOnInit() {
          }
          changeName() { //Create method to call from home.component.html
              this.itemName = this._data.getItemName();
          }
      }
  • Now let us add the click event on the button in src/app/home/home.component.html
    • <input type=”button” [value]=”buttonText” (click)=”changeName()”>
  • Run the application using
    • $ ng serve
  • When the app starts browse on the browser click the “Change Name” button and look into the text box and label values under it will change to “Orange” from “Apple”

 

We will see the next thing about Angular 5 App Deployment. Click Here

Advertisements

2 thoughts on “Angular 5 Services

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s