Gabriela Reyes
Gabriela Reyes

Reputation: 75

Communicating between two components using BehaviourSubject in Angular

So I have a table which I populate using data I get from my service, the methods inside this server are connected to a nodeJS API.

I tried to use a BehaviourSubject on my service which I initialized as undefined, since the data is get from the backend:

Service:

mport { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Voluntario } from "./voluntario.model";
import { BehaviorSubject } from "rxjs";

@Injectable({
  providedIn: "root"
})
export class VoluntarioService {
  private endpoint = "http://localhost:3000";
  public voluntariosChanged = new BehaviorSubject(undefined); //prueba refresh

  constructor(private httpClient: HttpClient) {}

  getVoluntarios() {
    return this.httpClient.get<Voluntario[]>(this.endpoint + "/voluntarios");
  }

  getVoluntario(id: string) {
    return this.httpClient.get<Voluntario>(
      this.endpoint + "/voluntarios/" + id
    );
  }

  createVoluntario(voluntario: Voluntario) {
    return this.httpClient.post<Voluntario>(
      this.endpoint + "/voluntarios",
      voluntario
    );
  }

  updateVoluntario(voluntario: Voluntario, id: string) {
    return this.httpClient.put<Voluntario>(
      this.endpoint + "/voluntarios/" + id,
      voluntario
    );
  }

  deleteVoluntario(id: string) {
    return this.httpClient.delete<Voluntario>(
      this.endpoint + "/voluntarios/" + id
    );
  }
}

What I wanna do is to refresh my list component whenever I create, edit or delete a new "Voluntario". Creating and Editing are done in a different component, and deleting is also on a different component. I tried first with the edit component, so I did this:

import { Component, OnInit, ViewChild } from "@angular/core";
import { VoluntarioService } from "../voluntario.service";
import { Voluntario } from "../voluntario.model";
import { ActivatedRoute, Params } from "@angular/router";

@Component({
  selector: "app-voluntarios-edit",
  templateUrl: "./voluntarios-edit.component.html",
  styleUrls: ["./voluntarios-edit.component.css"]
})
export class VoluntariosEditComponent implements OnInit {
  voluntarios: Voluntario[]; //pal refresh
  voluntario: Voluntario = {
    _id: null,
    volName: null,
    cedula: null,
    age: null,
    tel: null,
    sex: null,
    email: null
  };
  id: string;
  editMode = false;

  constructor(
    private voluntarioServicio: VoluntarioService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      this.id = params["id"];
      this.editMode = params["id"] != null;
      console.log(this.editMode);
    });
    //prepopulacion
    if (this.editMode) {
      this.voluntarioServicio.getVoluntario(this.id).subscribe(
        result => {
          console.log(result);
          this.voluntario = {
            _id: result._id,
            volName: result.volName,
            cedula: result.cedula,
            age: result.age,
            tel: result.tel,
            sex: result.sex,
            email: result.email
          };
        },
        error => console.log(error)
      );
    }
  }

  onSubmit() {
    if (this.editMode) {
      this.voluntarioServicio
        .updateVoluntario(this.voluntario, this.id)
        .subscribe(
          result => {
            console.log("Voluntario actualizado con exito", result);
            this.voluntarioServicio.voluntariosChanged.next(result);
          },
          error => console.log(error)
        );
    } else {
      this.voluntarioServicio.createVoluntario(this.voluntario).subscribe(
        result => {
          console.log("Voluntario creado con exito", result);
          this.voluntarioServicio.voluntariosChanged.next(result);
        },
        error => console.log(error)
      );
    }
    //refresh
  }
}

And finally on my list component I tried to call the voluntariosChanged BehaviourSubject on the ngOnInit:


  ngOnInit() {
    this.voluntarioService.getVoluntarios().subscribe(
      result => {
        this.voluntarios = result;
        console.log("Voluntario fetcheado con exito");
      },
      err => console.log(err)
    );

    this.voluntarioService.voluntariosChanged.subscribe(
      result => {
        this.voluntarios = result ;
      },
      err => console.log(err)
    );
  }

But it's not working... I'm really new to Angular and I've been googling about this but I guess I'm doing something wrong. Also, I have to point out that the List Component and the Edit Component are not Parent-Child, they are not related.

Upvotes: 1

Views: 1049

Answers (1)

Benjamin O. P.
Benjamin O. P.

Reputation: 106

One way to achieve this is using Subject instead of BehaviorSubject

public voluntariosChangedSource: Subject<Voluntario> = new Subject<Voluntario>();
public voluntariosChanged$: Observable<Voluntario> = this.voluntariosChangedSource.asObservable();

in your edit component use it so:

this.voluntarioServicio.voluntariosChangedSource.next(result);

in your list component you just have to call:

this.voluntarioService.voluntariosChanged$.subscribe(
    result => {
        this.voluntarios = result ;
    },
    err => console.log(err)
);

See in this answer https://stackoverflow.com/a/43351340/3733665 the difference between Subject and BehaviorSubject

Upvotes: 1

Related Questions