Creating a Service in Angular
Let's start learning about services by creating our own. To do this, in the test/src/app folder, create a file data.service.ts. Let our service be responsible for displaying some data on the screen.
Let's make a class for our service:
export class DataService {
}
Now we need the Injectable decorator. Using it will allow us to make it so that the service class can be injected into the component class. We will talk about injection in the next lesson. And now we import the required decorator:
import { Injectable } from '@angular/core';
export class DataService {
}
Let's apply it to our class:
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
}
Now let's make our class have some data. Usually, Angular apps load data from the server, but for learning purposes we'll use an array. Let's make it a private property:
export class DataService {
private data: string[] = ['a', 'b', 'c'];
}
Now let's write a method to get data:
export class DataService {
private data: string[] = ['a', 'b', 'c'];
getData(): string[] {
return this.data;
}
}
Our service is ready. In the next lesson we will connect it to the component class.
Create your own service that will return an array of objects with products:
[
{
name: 'prod1',
cost: 100,
},
{
name: 'prod2',
cost: 200,
},
{
name: 'prod3',
cost: 300,
},
]