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

标签 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”时刷新我的列表组件。创建和编辑是在不同的组件中完成的,删除也是在不同的组件中完成的。 我首先尝试使用编辑组件,所以我这样做了:

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 真的很陌生,我一直在谷歌上搜索这个问题,但我想我做错了什么。另外,我必须指出,列表组件和编辑组件不是父子组件,它们不相关。

最佳答案

实现此目的的一种方法是使用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主体和行为主体的区别

关于javascript - 在 Angular 中使用 BehaviourSubject 在两个组件之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58252765/

相关文章:

javascript - Uncaught Error : Component 'settings' : Unknown template value: [object Object]

javascript - MochaJS setTimeout ES6

javascript - 需要根据用户选择有条件地呈现具有 X 行数的部分

javascript - 在数据在 Angular 中可用之前阻止路由加载

php - 连接到客户端桌面应用程序的网站

Angular 2 - 在 Observable 中获取更改的 FormControl 的值

angular - 将控件从 Angular 中的组件添加到 html

Angular2 RC5 : Can't bind to 'Property X' since it isn't a known property of 'Child Component'

components - Xpages Null 或空字符串

C++:设计基于组件的实体系统——高级问题