Tartalomjegyzék

< Angular komponensek kommunikációja

Angular - Adatok átadása

Testvér komponensek között adatátadás

A BehaviorSubject osztályt használjuk.

Szolgáltatás

app/behav.service.ts
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);
  }
}

Komponens 1

app/comp1/comp1.component.ts
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)
  }
 
}
app/comp1/comp1.component.html
<p>comp1 works!</p>
<p>{{data}}</p>
<button (click)="sendDataToService()">Mehet</button>

Komponens 2

app/comp2/comp2.component.ts
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;
    })
  }
 
}
app/comp2/comp2.component.html
<p>comp2 works!</p>
 
<p>{{data}}</p>