< Angular komponensek kommunikációja
A BehaviorSubject osztályt használjuk.
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class BehavService { private data = new BehaviorSubject(''); currentData = this.data.asObservable(); constructor() { } setData(data:any) { this.data.next(data); } }
import { Component, OnInit } from '@angular/core'; import { BehavService } from '../behav.service'; @Component({ selector: 'app-comp1', templateUrl: './comp1.component.html', styleUrls: ['./comp1.component.scss'] }) export class Comp1Component implements OnInit { data: any = 'alma'; constructor(private behav: BehavService) { } ngOnInit(): void { } sendDataToService() { this.behav.setData(this.data) } }
import { Component, OnInit } from '@angular/core'; import { BehavService } from '../behav.service'; @Component({ selector: 'app-comp2', templateUrl: './comp2.component.html', styleUrls: ['./comp2.component.scss'] }) export class Comp2Component implements OnInit { data: any; constructor(private behav: BehavService) { } ngOnInit(): void { this.behav.currentData.subscribe(data => { this.data = data; }) } }
<p>comp2 works!</p> <p>{{data}}</p>