< Angular komponensek kommunikációja

Angular - Adatok átadása

Szerző: Sallai András

Copyright © Sallai András, 2023

Licenc: 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) } }
<p>comp1 works!</p> <p>{{data}}</p> <button (click)="sendDataToService()">Mehet</button>

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; }) } }
<p>comp2 works!</p> <p>{{data}}</p>