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

问题描述 投票:1回答:1

因此,我有一个表,该表使用从服务中获取的数据进行填充,该服务器内部的方法已连接到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真的很陌生,我一直在搜索这个,但是我想我做错了。另外,我必须指出,列表组件和编辑组件不是父子组件,它们是不相关的。

javascript angular components behaviorsubject
1个回答
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主题和行为主题之间的区别

© www.soinside.com 2019 - 2024. All rights reserved.