gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:30:07 25 4
gpt4 key购买 nike

因此,我有一个使用从服务中获取的数据填充的表,该服务器内的方法连接到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com