Compartir datos entre componentes angulares

Problema

Como resultado de trabajar con el marco Angular, descomponemos nuestra aplicación web. Y, por lo tanto, tenemos una situación en la que necesitamos transferir datos entre componentes.





@Aporte ()

Para pasar datos a un componente hijo, podemos usar un decorador @Input()



. Nos permitirá pasar datos del componente padre al componente hijo. Veamos un ejemplo simple:





import { Input, Component} from '@angular/core';
      
@Component({
    selector: 'app-child',
    template: `<h1>Title: {{ title }}</h1>`
})
export class ChildComponent { 
    @Input() title: string;
}
      
      



En el componente hijo, hemos "decorado" la propiedad que necesitamos title



. No olvide importar el decorador:





import { Input} from '@angular/core';
      
      



Solo queda pasar el parámetro title



al componente secundario del padre:





import { Component } from '@angular/core';
      
@Component({
    selector: 'app-component',
    template: `<app-child [title]="title" [userAge]="age"></app-child>`
})
export class AppComponent { 
    public title = 'Hello world!';
}
      
      



[title]="title"



, title="Hello world"



. , ?





@Output()

@Output()



. , :





import { Component } from '@angular/core';
       
@Component({
    selector: 'app-counter',
    template: `<h1>Count: {{ count }}</h1>
              <app-add (buttonClick)="onAdd()"></app-add>`
})
export class AppCounter { 
    public count = 0;

public onAdd(): void {
    this.count++;
}

}
      
      



import { Component, EventEmitter, Output } from '@angular/core';

@Component({
    selector: 'app-add',
    template: `<button (click)="add()"></button>`;
})
export class AppAdd { 
    @Output() buttonClick = new EventEmitter();

		public add(): void {
    	this.buttonClick.emit();
		}
}
      
      



. AppAdd



click



, add()



. this.buttonClick.emit() buttonClick



AppCounter



. EventEmitter



:





import { EventEmitter } from '@angular/core';
      
      



"", . :





import { Component } from '@angular/core';

@Component({
    selector: 'app-better-counter',
    template: `<h1>Count: {{ count }}</h1>
							<app-buttons (buttonClick)="onChange($event)"></app-buttons>`
})
export class BetterCounterComponent { 
    public count = 0;

		public onChange(isAdd: boolean): void {
      if (isAdd) {
        this.count++;
      } else {
          this.count--;
      }
	 }
}
      
      



import { Component, EventEmitter, Output } from '@angular/core';

@Component({
    selector: 'app-buttons',
    template: `<button (click)="change(true)"></button>                
							 <button (click)="change(false)"></button>`
})
export class ButtonsComponent { 
    @Output() buttonClick = new EventEmitter<boolean>();

		public change(change: boolean): void {
    	this.buttonClick.emit(change);
		}
}
      
      



:





  • new EventEmitter<



    boolean>()







  • emit



    this.buttonClick.emit(change)







  • $event



    (buttonClick)="onChange($event)"







@Input()



@Output()



, , , .., .





RxJs

. , :





import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class SimpleService {
    public count$ = new Subject<number>();

		public changeCount(count: number) {
   		this.count$.next(count); 
  	}
}
      
      



. count$



. - . Subject



. Subject



- , . , Subject



. , count



:






import { SimpleService } from './services/simple.service.ts';

@Component({
    selector: 'app-any',
    template: ``
})
export class AnyComponentComponent { 
    constructor(
          private readonly simpleService: SimpleService
    ) {}
  
  	public setAnyCount(): void {
      this.simpleService.changeCount(Math.random());
		}
}
      
      



Math.random()



. :





import { Component, OnInit } from '@angular/core';
import { SimpleService } from './services/simple.service.ts';

@Component({
    selector: 'app-other',
    template: ``
})
export class OtherComponentComponent implements OnInit { 
    constructor(
       private readonly simpleService: SimpleService
    ) {}
  
    ngOnInit(): void {
      this.simpleService.count$.subscribe((count) => this.log(count));
    }

    private log(data: number): void {
  		console.log(data);
    }

}
      
      



count



, count$.next(...)



- subscribe



. - . , , . , . log()



, . - , . , count$



OnDestroy



. unsubscribe()



:





import { Component, OnInit, OnDestroy } from '@angular/core';
import { SimpleService } from './services/simple.service.ts';
import { Subsription } from 'rxjs';

@Component({
    selector: 'app-other',
    template: ``
})
export class OtherComponentComponent implements OnInit, OnDestroy {
   	private subs: Subsription;

    constructor(
      private readonly simpleService: SimpleService
    ) {}

    ngOnInit(): void {
      this.subs = this.simpleService.count$.subscribe((count) => this.log(count));
    }

    ngOnDestroy(): void {
  		this.subs.unsubscribe();
		}

    private log(data: number): void {
  		console.log(data);
    }
}
      
      



Podemos suscribirnos a muchos temas de un componente, suscribirnos al mismo tema de diferentes componentes.





Salir

Podemos compartir datos entre los componentes que utilizan @Input()



, @Output()



y RxJs. En este artículo, omití store



, ya que el artículo está destinado a principiantes. Te aconsejo que practiques este tema para mejorar tus habilidades.








All Articles