使用Angular中的BehaviourSubject在两个组件之间进行通信

时间:2019-10-05 22:18:59

标签: javascript angular components behaviorsubject

因此,我有一个表,该表使用从服务中获取的数据进行填充,该服务器内的方法已连接到nodeJS API。

由于数据是从后端获取的,所以我尝试在服务上使用BehaviourSubject并将其初始化为未定义:

服务:

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
    );
  }
}

我想做的是每当我创建,编辑或删除新的“ Voluntario”时刷新列表组件。创建和编辑在不同的组件中完成,而删除也在不同的组件中。 我首先尝试使用edit组件,所以做到了:

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
  }
}

最后在清单组件中,我尝试在ngOnInit上调用voluntariosChanged BehaviourSubject:


  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)
    );
  }

但是它不起作用...我对Angular真的很陌生,我一直在搜索这个问题,但我想我做错了什么。另外,我必须指出,列表组件和编辑组件不是父子组件,它们是不相关的。

1 个答案:

答案 0 :(得分:0)

一种实现此目的的方法是使用Subject而不是BehaviorSubject

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

在您的编辑组件中使用它,以便:

this.voluntarioServicio.voluntariosChangedSource.next(result);

在列表组件中,您只需调用:

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

请参见此答案https://stackoverflow.com/a/43351340/3733665,Subject和BehaviorSubject之间的区别