Home Angular6 How Angular 6 Service Works?

How Angular 6 Service Works?

by therichpost
Published: Last Updated on 0 comment
angular 6 service works

Hello to all, welcome to therichpost.com. In this post, I will tell you, How Angular 6 Service Works?

First, I will show working picture:

How Angular 6 Service Works

Services are injected and In my service, I am getting data and  the backend is php. I used HttpClient get api to get the data.

We can also get the data without services but for clean code and better understanding, we make services.

Here is the complete working and tested code and you need to add you Angular 6 app:


1. Very first, you need to make app.service.ts file into your app folder and her is the code for this:

I used Observable to  transfer data into angular app and getPosts will return an observable. An observable data  used to throughout the application.

import { Injectable } from '@angular/core'; 
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
export class appService { 

constructor(private http:HttpClient) { }
public getPosts():Observable<Idata[]>
        return this.http.get<Idata[]>('http://localhost/mypage.php');


2. After it, you need to add below code into your app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }


3. After that, you need to add below code into your app.component.ts file:

import { Component, OnInit } from '@angular/core';
import { appService } from './app.service'; 
import { Observable } from 'rxjs/Observable';
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [appService] 
export class AppComponent {
    public data : any ;
    constructor(private appservice: appService) {} 
    ngOnInit() {
    this.appservice.getPosts().subscribe(value => {


4. Finally, add below code into your app.component.html file:

<div class="jumbotron text-center">
  <h1>Angular 6 services
<div class="container">
  <ul class="list-group" *ngFor="let post of data">
    <li class="list-group-item">{{ post.id }}</li>


5. I know, you always see bootstrap code in my Angular app, so to all bootstrap into you Angular 6 app, please follow below link:

 Add Bootstrap 4 to Angular 6 

If you have any query related to this post, then please ask questions or comment below.

You may also like

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.