⊗jsagPmSvUs 76 of 97 menu

Using a Service in Angular

In the previous tutorial we created our own service DataService. Let's now import it into the component:

import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { DataService } from './data.service'; // here there at this point near at hand

In the decorator @Component in the property providers we need to specify our service:

@Component({ ..... providers: [ DataService ] // here there at this point near at hand })

Now we will use a special approach called dependency injection (dependency injection). Its essence is that in the component constructor we can pass our service as a parameter and it will automatically get into the private property of our component. Look at the code:

export class AppComponent { constructor(private dataService: DataService) { // inject dependency console.log(this.dataService); // service in private property } }

The injection works for our service because we previously applied the Injectable decorator to it.

Let's now get data from our service in the component class constructor by calling the appropriate method:

export class AppComponent { public data: string[] = []; constructor(private dataService: DataService) { this.data = this.dataService.getData(); } }

Let's output the obtained data in the component template:

<ol> <li *ngFor="elem of data"> {{ elem }} </li> </ol>

Get the products from your service in the component and display them in the component template.

Make a method for adding a new product in your service. Make a button in the component that will add a new product when clicked.

Create a form with two inputs and a button that, when clicked, will add a new product.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline