Angular 6 Service – with Observable Data for Asynchronous Operation

Angular 6 Service – with Observable Data

Angular Component is used to present data and delegate data access to a service. Angular Services are a great way to share data among classes. So in the tutorial, we introduce how to create Angular Service and use Observable class of RxJS library for asynchronous operation in Angular Service’s implementation.

Related posts:
Angular 6 Component – How to create & integrate New Angular 6 Component
Angular 6 Routing/Navigation – with Angular Router Service
How to Integrate Angular 6 & SpringBoot 2.0 RestAPI – SpringToolSuite

Technologies

  • Node.js – version v10.4.0
  • Angular – version 6
  • Visual Studio Code – version 1.24.0

Practice

Generate Project Structure

Generate Angular Project:

ng new angular6-service

angular-6-services + create-angular6- project

Generate Customer Component:

ng generate component customer

angular-6-services + create-a-component-customer

Generate Customer Service:

ng generate service customer

angular-6-services + create-an-angular-6-service-customer

Generate Customer classes:

ng generate class customer
ng generate class mock-customers

angular-6-services + generate-angular-6-class

-> Project Structure:

angular-6-services + angular-project-structure

Implement Mock Data

Create data class in src/app/customer.ts file:


export class Customer {
    id: number;
    firstname: string;
    lastname: string;
    age: number
}

Mock Customer data in src/app/mock-customers.ts file:


import { Customer } from './Customer';
 
export const CUSTOMERS: Customer[] = [
      {id: 1, firstname: 'Mary', lastname: 'Taylor', age: 24},
      {id: 2, firstname: 'Peter', lastname: 'Smith', age: 18},
      {id: 3, firstname: 'Lauren', lastname: 'Taylor', age: 31}
];

Implement Angular Service

-> First look src/app/customer.service.ts file:


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

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

  constructor() { }
}

@Injectable decorator is a marker metadata that marks a class as available to Injector for creation.

Now, modify customer.service.ts file as below:


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

import { Customer } from './customer';
import { CUSTOMERS } from './mock-customers';

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

  constructor() { }

  getCustomers(): Customer[] {
    return CUSTOMERS;
  }
}

Update Angular Components

Firstly, import CustomerService:


import { CustomerService } from '../customer.service';

Inject the CustomerService:


constructor(private customerService: CustomerService) { }

-> Now, We can use customerService as a CustomerService injection.

Fetch data from CustomerComponent via CustomerService:


  ngOnInit() {
    this.customers = this.customerService.getCustomers();
  }

Full code in customer.component.ts file:


import { Component, OnInit } from '@angular/core';
import { CustomerService } from '../customer.service';
import { Customer } from '../customer';

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

  customers: Customer[];

  constructor(private customerService: CustomerService) { }

  ngOnInit() {
    this.customers = this.customerService.getCustomers();
  }
}

In customer.component.html file, use Angular *ngFor to display data:

<h1>Customer List</h1>
<ul>
  <li *ngFor="let customer of customers">
    {{ customer | json }}
  </li>
</ul>

In AppComponent component, add selectỏr app-customer tag in style file app.component.html:

<div>
    <app-customer></app-customer>
</div>

-> Result:

angular-6-services + load-data-from-service-synchronize-operation

Observable Data

What is the problem with above the service implementation?
-> CustomerService.getCustomers() is a synchronous method. It will Not work with real application (with remote APIs, waiting time for responses).

Solution:
-> Observable is a key class in the RxJS library which provides asynchronous operation.

Now, the sourcecode can be updated as below:

– With CustomerService, modify customer.component.ts class:


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

import { Observable, of } from 'rxjs';

import { Customer } from './customer';
import { CUSTOMERS } from './mock-customers';

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

  constructor() { }

  getCustomers(): Observable {
    return of(CUSTOMERS);
  }
}

– With CustomerComponent, modify customer.component.ts class:


import { Component, OnInit } from '@angular/core';
import { CustomerService } from '../customer.service';
import { Customer } from '../customer';

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

  customers: Customer[];

  constructor(private customerService: CustomerService) { }

  ngOnInit() {
    this.customerService.getCustomers()
    .subscribe(customers => this.customers = customers);
  }
}

SourceCode

How to run the below sourcecode:


1. Download Angular-6-Service.zip file -> Then extract it to Angular-6-Service folder.
2. Go to Angular-6-Service folder
3. Run the app by commandline: ng serve --open

-> Source Code:

Angular-6-Service

51 thoughts on “Angular 6 Service – with Observable Data for Asynchronous Operation”

  1. I like the valuable information you provide on your articles.
    I’ll bookmark your blog and test once more here frequently.
    I am rather certain I’ll be informed lots of new
    stuff proper right here! Good luck for the following!

  2. hello there and thank you for your information – I’ve
    definitely picked up something new from right here. I did however expertise a few technical points using this web site,
    since I experienced to reload the web site a lot of
    times previous to I could get it to load correctly.
    I had been wondering if your hosting is OK? Not that I am complaining, but slow
    loading instances times will very frequently affect your placement in google and
    can damage your high quality score if advertising and marketing with Adwords.

    Anyway I’m adding this RSS to my e-mail and can look out for much more of your respective interesting content.
    Ensure that you update this again soon.

  3. Hello this is somewhat of off topic but I was wondering if blogs use WYSIWYG
    editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding knowledge so I
    wanted to get advice from someone with experience.
    Any help would be greatly appreciated!

  4. Pretty nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed surfing around your blog posts.
    After all I will be subscribing to your feed and I hope
    you write again soon!

  5. Hey There. I found your weblog using msn. That is a very
    neatly written article. I will be sure to bookmark it and come
    back to read extra of your useful info. Thanks for
    the post. I will certainly return.

  6. Thanks , I’ve just been searching for information about this topic
    for a while and yours is the best I’ve discovered till
    now. But, what concerning the conclusion? Are you sure about
    the source?

  7. Hi there, I believe your site might be having internet browser compatibility issues.

    When I look at your web site in Safari, it looks fine however, if opening in IE, it’s got some overlapping issues.
    I simply wanted to give you a quick heads up!
    Other than that, excellent website!

  8. After I initially left a comment I seem to have clicked the -Notify me when new comments are added- checkbox and now whenever a comment is added I recieve 4 emails with the same comment.
    Is there a means you can remove me from that service?
    Appreciate it!

  9. Нi are using Wordрress ffor youhr site platform? I’m new to the blog ԝorld but I’m trуing to get started and set up
    my own. Do you require any html coding expeгtіse
    to make your own blog? Any help woulԁ be really appreciateɗ!

  10. Thank you for another informative website. Where
    else may I am getting that kind of information written in such a perfect method?

    I have a mission that I am simply now working on, and I’ve been at the glance out for such information.

  11. I was very pleased to find this website. I want to to thank
    you for ones time for this wonderful read!!

    I definitely liked every bit of it and I have you
    book marked to see new stuff on your site.

  12. Hey there are using WordPress for your blog platform?

    I’m new to the blog world but I’m trying to get started and create my own. Do you require any html coding knowledge
    to make your own blog? Any help would be greatly appreciated!

  13. You really make it seem so easy together with your presentation however I to find
    this topic to be actually something that I think I’d never understand.
    It seems too complicated and very large for me. I’m looking ahead for your subsequent post, I will try to get the hold of it!

  14. Fantastic blog! Do you have any hints for aspiring writers?
    I’m planning to start my own site soon but I’m a little
    lost on everything. Would you advise starting with a free platform like WordPress or go
    for a paid option? There are so many choices out there that I’m completely overwhelmed ..

    Any recommendations? Thanks!

  15. Nice post. I was checking constantly this weblog and I’m inspired!
    Very helpful information specifically the remaining
    section 🙂 I deal with such info a lot. I was seeking this particular information for a long time.
    Thanks and good luck.

  16. Indihome Jakarta Timur sekarang datang dengan service pasang jaringan Indihome lewat cara online, anda
    tidak butuh hadir ke kantor indihome untuk mengerjakan register penempatan indihome.

    Ini sebagai wujud service digital paling depan dari Indihome Jakarta Timur untuk meringankan orang Jakarta Timur yang pengin nikmati jaringan internet cepat indihome.
    Dengan memakai Technologi Fiber Optik, kami menjajakan sejumlah pelayanan paket internet seperti Singgel
    Play, Dual Play juga Triple Play. Diluar itu kami pula tawarkan sejumlah Add On Favorit buat anda rasakan sama keluarga.

  17. I’m really inspired long with your writing abilities as smartly as with thhe layout
    in your weblog. Is that this a paid subject oor did you customize it your self?
    Anyway stay upp the nice high quality writing,
    it’s rare to see a nice weblog like this one these days..

  18. Have you ever considered creating an ebook or guest authoring on other sites?

    I have a blog based on the same information you discuss and
    would love to have you share some stories/information. I know my subscribers would value your work.
    If you are even remotely interested, feel free to shoot me an email.

  19. Hi, I believe your web site could possibly
    be having browser compatibility problems. When I take a look at your website
    in Safari, it looks fine however, if opening in I.E., it has some overlapping issues.
    I merely wanted to provide you with a quick heads up!

    Aside from that, wonderful website!

  20. Unquestionably consider that that you stated.
    Your favorite justification appeared to be on the net the simplest
    thing to keep in mind of. I say to you, I certainly get annoyed
    while people think about concerns that they just do not recognise about.
    You managed to hit the nail upon the highest and also outlined out the whole thing without having
    side-effects , other folks could take a signal.
    Will probably be back to get more. Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *