DEV Community

Cover image for Share data to all component via service use NgZone, Subject
Angga Lesmana
Angga Lesmana

Posted on

Share data to all component via service use NgZone, Subject

There are some cases in Angular that you should know to send data between components or to all components, which many of us often use @Input @Output or we can use global variable and via service
here I'm gonna only explain one first through service (ngZone)
let we create some service
data.service.ts

//we should import
import { Injectable, NgZone } from '@angular/core';
import { Subject } from 'rxjs';

private dataStr = new Subject<any>()
data$ = this.dataStr.asObservable()

constructor(private ngZone: NgZone) { }


  sendDataUrl(data: any){
   return this.ngZone.run(() => {
      this.dataStr.next(data)
    } )
  }

Enter fullscreen mode Exit fullscreen mode

Image description

and let we create component to send data via service
first we import and inject the service that we created earlier


import { UrlnavService } from '../../../../shared/urlnav.service';
//here myservice name UrlnavService

constructor(private urlnavService: UrlnavService){}
//inject the service

 sendDataParams(){
    this.urlnavService.sendDataUrl(this.url)
 }
//and create method to send data 

Enter fullscreen mode Exit fullscreen mode

trust the data will send into Subject data,
After we send data from component1, now we take the data that has been sent to the service in another component

dont forget we must import the service and inject it like in component before

import { UrlnavService } from './shared/urlnav.service';
constructor(private navurlService: UrlnavService){}

//here im getting data via ngOnInit 
 ngOnInit() {
    this.navurlService.data$.subscribe((data: any) => {
      this.url = data
      console.log(this.url)
    })
  }

Enter fullscreen mode Exit fullscreen mode

Image description

then we can share data to all component via service

the other way to share data iscomingsoon

Top comments (0)