Hello Devs,
In this tutorial, we are going to learn how to create service in angular 10.
There are set of commands provided by angular 10 application. From there, we will use that command to creating service in angular 10 application.
Follow this step by step guide given below:
Create Service
ng g service Post
src/app/post.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class PostService {
constructor() { }
getPosts(){
return [
{
id: 1,
title: 'Angular 10 Http Post Request Example'
},
{
id: 2,
title: 'Angular 10 Routing and Nested Routing Tutorial With Example'
},
{
id: 3,
title: 'How to Create Custom Validators in Angular 10?'
},
{
id: 4,
title: 'How to Create New Component in Angular 10?'
}
];
}
}
Use Service in Component
src/app/app.component.ts
import { Component } from '@angular/core';
import { PostService } from './post.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'appNewService';
posts = [];
constructor(private postService: PostService){
this.posts = postService.getPosts();
}
}
View File
src/app/app.component.html
<h1>How to create service in angular 10 using cli - Rathorji.in</h1>
<ul>
<li *ngFor="let post of posts">
<strong>{{ post.id }})</strong>{{ post.title }}
</li>
</ul>
Run this command:
ng serve
I hope this example helps you.