Friday 29 January 2021

How to pass data between two components in angular

 Hello Guys, today in this blog we will learn how to pass data between components.

Suppose there is a component Customer Registration and Dashboard. We need to pass data from Customers to the Dashboard. We will have to create a service so that it will also the data sharing.

Ceate customer.service.ts


import { Injectable } from '@angular/core';
import { BehaviorSubjectObservable } from 'rxjs';
@Injectable()
export class CustomerRegistartionService {
    public RenewCount = new BehaviorSubject<number>(0);
    getRenewCount(): Observable<number> {
        return this.RenewCount.asObservable();

    }
    setRenewCount(valnumber) {
        this.RenewCount.next(val);
    }
    public Customer = new BehaviorSubject<any>([]);
    getCustomer():Observable<any>{
        return this.Customer.asObservable();
    }
    setCustomer(val:any){
        this.Customer.next(val);
    }
    public Revenue = new BehaviorSubject<any>([]);
    getRevenue():Observable<any>{
        return this.Revenue.asObservable();
    }
    setRevenue(val : any){
        this.Revenue.next(val)
    }
} 


Here we need to get and set the value which we need to pass
we use set from the source component and use get in the destination component.

THIS IS OUR SOURCE COMPONENT

GetCustomerList() {
        this.loading = true;
        this.http.get('api/CustomerRegistration/GetCustomerList')
            .subscribe(res => {
                this.CustomerList = res;
                this.findSum(this.CustomerList)
                this.custservice.setRenewCount(this.CustomerList.filter(a => a.Remaining <= 6).length);
                this.custservice.setCustomer(this.CustomerList);

                this.loading = false;
            }, err => {
                this.messageService.add({ severity: 'error'summary: 'Error Message'detail: err.error });
                this.loading = false;
            })
    }

THIS IS OUR DESTINATION

ngOnInit(){
        this.custservice.getRenewCount()
        .subscribe(val =>{
            this.count = val;
        })
        this.custservice.getCustomer()
        .subscribe(val=>{
            this.loading=true;
            this.customerval;
            console.log(this.customer)
            this.loading=false;
        })