Sharing data between components
Service:
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AppService { counter = 1; count: BehaviorSubject<number>; constructor() { this.count = new BehaviorSubject(this.counter); } nextCount() { this.count.next(++this.counter); } }
Now components can consume service to access shared data. For example, in a component, service can be consumed as shown in the next listing:
export class Appchild2Component implements OnInit { count: number; constructor(private appsevice: AppService) { } ngOnInit() { this.appsevice.count.subscribe(c => { this.count = c; }); } nextCount() { this.appsevice.nextCount(); } }
We are subscribing to service and reading the value of count in the local variable. In addition, there is a function that increments the count. On the template, you can display and increment shared data as shown in the next code listing:
<h2>Count in component2 = {{ count }}</h2> <button (click)='nextCount()'>Next Count from component2</button>
In this way, you can consume service in as many components as possible and everywhere they will share the same data from the service. For your reference you can find working stackblitz here:
https://stackblitz.com/github/debugmodedotnet/componnetcommunicationwithservice
Parent child component relationship:
https://fireship.io/lessons/sharing-data-between-angular-components-four-methods/
In my opinion
----------------------------------------shared service--------------------------------------------------------------------------------
//check login in login constructor
using subscribe in constructor
Comments
Post a Comment