Passing Data From Service To Component In Angular

In this article I will explain about using Angular services,  a class with specific operations for specific purposes, which is very useful in sharing the data between components.
 
This article is in continuation of my previous article, Navigating from one component to another component using a router. You may be wondering why am I covering this topic in this article. Well, for navigating in my previous article, I have never used any Angular Services, as well as I didn't use MVC architecture. In that article, the component is not only responsible for displaying the data, it is also taking the responsibility of generating the data, which is not the function part of it.
 
So, the components should only be responsible to use the given data and display it which is generated from the services. So, in this article, I have used Angular services, in which users can use services to inject into components so that the components will be able to use only the data which is coming from services.
 
Now, we need to create a model class so that we can use the class properties for the specific purposes. I have created a class using the command as mentioned below,
   
ng generate class mlproduct
 
Passing Data From Service To Component
 
By using the above command, a model file has been created and I have added the properties that are required for the class file.
  1. export class mlProductList {  
  2.    productname: string;  
  3.    productdescription: string;  
  4.    productdescription01: string;  
  5.    productcost: string;  
  6.    productsrc: string;  
  7.    total: number;  
  8.    quantity: number;  
  9. }  
So, coming to the next step, we need to create the service. We can create a service by using this command.
 
ng generate service Myservice
 
Passing Data From Service To Component
 
After generating the service file, open myservice.service.ts file and add the code as below.
  1. import { Injectable } from '@angular/core';  
  2. import { mlProductList } from './mlProduct';  
  3. @Injectable({  
  4.    providedIn: 'root'  
  5. })  
  6. export class MyserviceService {  
  7.    createproduct(data: mlProductList): void {  
  8.    throw new Error("Method not implemented.");  
  9. }  
  10. productList: mlProductList[];  
  11.    getproductlist() {  
  12.    this.productList = [{  
  13.       total: 0,  
  14.       quantity: 0,  
  15.       productname: 'nokia5.1',  
  16.       productdescription: '3000 mah',  
  17.       productdescription01: '4 GB RAM 64 GB Internal storage',  
  18.       productcost: '12,000',  
  19.       productsrc: 'assets/images/nokia5.1.jpg',  
  20.       },  
  21.       ];  
  22.    return this.productList;  
  23.  }  
  24. }  
The next step is to add these services in app.module.ts file, so open app.module.ts file and add the code as below.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { AppRoutingModule } from './app-routing.module';  
  4. import { AppComponent } from './app.component';  
  5. import { FormsModule } from '@angular/forms';  
  6. import { NavigationComponent } from './navigation/navigation.component';  
  7. import { ProductdescriptionComponent } from './productdescription/productdescription.component';  
  8. import { CartComponent } from './cart/cart.component';  
  9. import { MyserviceService } from './myservice.service';  
  10. @NgModule({  
  11.    declarations: [  
  12.    AppComponent,  
  13.    NavigationComponent,  
  14.    ProductdescriptionComponent,  
  15.    CartComponent  
  16. ],  
  17. imports: [  
  18.    BrowserModule,  
  19.    FormsModule,  
  20.    AppRoutingModule  
  21.    ],  
  22.    providers: [MyserviceService],  
  23.    bootstrap: [AppComponent]  
  24. })  
  25. export class AppModule { }  
Until now, we have added the following code as mentioned above. Still, some more changes have to be made in-order to get it done. So, now open productdescription.component.ts file and replace the missing codes and import the service files along with replaced codes.
  1. import { Component, OnInit, AfterViewInit } from '@angular/core';  
  2. import { ActivatedRoute, RouterOutlet, Router } from '@angular/router';  
  3. import { mlProductList } from '../mlProduct';  
  4. import { MyserviceService } from '../myservice.service';  
  5.    @Component({  
  6.       selector: 'app-productdescription',  
  7.       templateUrl: './productdescription.component.html',  
  8.       styleUrls: ['./productdescription.component.css']  
  9.    })  
  10. export class ProductdescriptionComponent implements OnInit {  
  11.    public product: mlProductList[];  
  12.    public description: mlProductList;  
  13.    constructor(  
  14.       private srvCart: MyserviceService,  
  15.       private activatedRoute: ActivatedRoute  
  16.    ) { }  
  17. ngOnInit() {  
  18.    this.product = this.srvCart.getproductlist();  
  19.    this.activatedRoute.params.subscribe(param => {  
  20.    // tslint:disable-next-line: no-string-literal  
  21.    this.description = this.product[param['id']];  
  22.    });  
  23.  }  
  24. }  
Now, open the navigation.component.ts file, add the following code, and import the services along with below mentioned code.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { MyserviceService } from '../myservice.service';  
  3. @Component({  
  4.    selector: 'app-navigation',  
  5.    templateUrl: './navigation.component.html',  
  6.    styleUrls: ['./navigation.component.css']  
  7. })  
  8. export class NavigationComponent implements OnInit {  
  9.    public product: any;  
  10.    constructor(  
  11.       private srv: MyserviceService,  
  12.       ) {  
  13.    }  
  14. ngOnInit() {  
  15.    this.product = this.srv.getproductlist();  
  16.    }  
  17. }  
At last now here comes the final step. Open cart.component.ts file and add the mentioned code and import the services along with the below code.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { MyserviceService } from '../myservice.service';  
  3. @Component({  
  4.    selector: 'app-cart',  
  5.    templateUrl: './cart.component.html',  
  6.    styleUrls: ['./cart.component.css']  
  7. })  
  8. export class CartComponent implements OnInit {  
  9.    constructor(private srvCartList: MyserviceService) {  
  10.    }  
  11.    ngOnInit() {  
  12.  }  
  13. }  
Now run the Angular application by using this command and we can see the output,
 
ng serve –open
 
Passing Data From Service To Component
 
Passing Data From Service To Component
 
We can see the same output which we got in the previous article. This time, we can see that the data is coming from an Angular Service and our component is only performing a single function of displaying the data.


Similar Articles