Search code examples
javascriptangularobjectbehaviorsubject

How I can access a value from a object passed by behaviorsubject


I try to pass values of my component "Modal-accion-reforma" to the component "entidad-tablas-buscador". for that, I see that tutorial abouth behaviorsubject (the tutorial is in spanish) https://www.youtube.com/watch?v=Sr1tg_NrQFk&t=573s

I was successfully pass the value in the another component (I can print the values in the HTML using Async), but the problem is I don't know how to access its variables in the typescript. The tutorial only tells me how to paint it in the html.

My service: accion-reforma

models:

export interface tipoInit {
  _tipoEnumCod: string,
  _numNorma: number,
  _tipoNormaId: string,
  _listEntidades: []
};  

const inittipoInit: tipoInit = {
  _tipoEnumCod: "CREA",
  _numNorma: 1,
  _tipoNormaId: "a",
  _listEntidades: []
}

functions:

private tipo$ = new BehaviorSubject<tipoInit>(inittipoInit);

get selectedtipo$():Observable<tipoInit>{
  return this.tipo$.asObservable();
}

setTipo(tipo:tipoInit):void{
  this.tipo$.next(tipo)
}

My emit component: Modal-accion-reforma

    tipos: tipoInit[] =[];
    selection!: tipoInit;

  constructor(
    private accionReformaService: AccionReformaService, 
    public dialogRef: MatDialogRef<ModalAccionReformaComponent>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData,
  ) {}

  ngOnInit(): void {
    this.accionReformaService.selectedtipo$.subscribe((tipoint: tipoInit) => this.selection = tipoint)
  }

  Ir_accion_reforma(tipoEnumCod:string, numNorma:any, tipoNormaId:any ){
   this.selection._tipoEnumCod = tipoEnumCod
   this.selection._numNorma = numNorma
   this.selection._tipoNormaId = tipoNormaId
   this.accionReformaService.setTipo(this.selection);
 }

My receptor component: entidad-tablas-buscador

   selectedtipo$ = this.accionReformaService.selectedtipo$;

  constructor(private accionReformaService: AccionReformaService, 
    private _formBuilder: FormBuilder, 
    private entidadService: EntidadService) {}

  ngOnInit(): void {


    console.log("AHORA VEREMOS: "+ this.selectedtipo$) 
/* I can't access  _tipoEnumCod,  _numNorma, _tipoNormaId, _listEntidades  */

  }

HTML entidad-tablas-buscador (I can access at my values emited)

<label fxFlex="30%">Nivel de la entidad: {{(selectedtipo$ | async)?._tipoEnumCod}}</label>

Solution

  • The purpose of observable in Angular is to work with asynchronous code by subscribing to its changes. You should subscribe to observable this.selectedtipo$ in order to get the data from it.

    If you need the data in component try modifying your ngOnInit hook in entidad-tablas-buscador component to this:

    const subscription = this.selectedtipo$.subscribe((selectedTipo) => {
       console.log(selectedTipo);
    })
    

    And make sure to unsubscribe (delete subscriptions) to avoid memory leaks and unexpected behavior.

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
    

    You can also use take or takeUntill operators.

    On the other hand, if you need that data only in template, you can use 'async' pipe in html:

    <h2>Selected tipo </h2>
    <span> {{ selectedtipo$ | async }} </span>
    

    In this case you still need to have a property in component, but for this you can ignore the unsubscribing on destroy.