Welcome Guest! (App Version 3.1)

websitnero logo name

Getting Data via Service

How to get data from a Service?

To get data from the service rather than keeping it at the component you need to do the following steps:

  1. First create a service
  2. Make a function in service to return some data from service
  3. Create an html element like button to fire an event, corresponding to which data has to be fetched
  4. When this event is fired (or button clicked), catch the event in logic file (.ts) and make a call to the function present in service which will then return data to the logic (.ts) file.
  5. Use this data in view (.html) to be shown to the end user.

Practical Example of "Getting data via Services"

Please follow the mentioned steps:

  1. Create a compennt named 'home'
  2. Add the home component in the app.component.html file removing all boilerplate code there.
  3. Create a service named 'people' - from where we will try to fetch data of 5 people.

  1. Add a button in app.component.html and write a function in the logic file (app.component.ts) to fetch data from service - to be shown in the view of compnoent.

home.component.html

<button (click)="alpha()">Click Me</button>

<ul>
  <li *ngFor="let x of people">
    {{x.name}}, {{x.age}}, {{x.country}}
  </li>
</ul>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { PeopleService } from './../../services/people.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  people = [];

  constructor(private peopleService: PeopleService) { }

  ngOnInit() {
  }

  alpha() {
    this.people = this.peopleService.getPeopleData();
  }

}

people.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class PeopleService {

  peopleData = [
    {name: 'Jack', age: 29, country: 'USA'},
    {name: 'Rosy', age: 23, country: 'UK'},
    {name: 'Peter', age: 29, country: 'Austria'},
    {name: 'Robert', age: 47, country: 'Canada'},
    {name: 'Lila', age: 42, country: 'India'}
  ];

  constructor() { }

  getPeopleData() {
    return (this.peopleData);
  }
}

  1. You'll get the following result.

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.