How to notify about data update to other component.

  we can update about data changes to any component using bellow simple method

1) Service to publish and receive data

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

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

    private fooSubject = new Subject<any>();

    publishSomeData(data: any) {
        this.fooSubject.next(data);
    }

    getObservable(): Subject<any> {
        return this.fooSubject;
    }
}

2) Data sending component

@Component({
    selector: 'app-home',
    templateUrl: 'home.page.html',
    styleUrls: ['home.page.scss']
})
export class HomePage {

    constructor(private globalFooService: GlobalFooService) {
    }

    onSomeButtonClick() {
        this.globalFooService.publishSomeData({
            foo: 'bar'
        });
    }
}


3) Data receiving component

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
})
export class AppComponent {

    constructor(private globalFooService: GlobalFooService) {
        this.initializeApp();
    }

    initializeApp() {
        // other code

        this.globalFooService.getObservable().subscribe((data) => {
            console.log('Data received', data);
        });
    }
}

Comments

Popular posts from this blog

how to save images with angular nodejs

How to export data to excel sheet with colors and style in angular.