[[oktatas:web:angular:angular_komponensek_kommunikacioja|< Angular komponensek kommunikációja]] ====== Angular - Adatok átadása ====== * **Szerző:** Sallai András * Copyright (c) Sallai András, 2023 * Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]] * Web: https://szit.hu ===== Testvér komponensek között adatátadás ===== A BehaviorSubject osztályt használjuk. ==== Szolgáltatás ==== 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 ==== 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) } }

comp1 works!

{{data}}

==== Komponens 2 ==== 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; }) } }

comp2 works!

{{data}}