gpt4 book ai didi

Angular rxjs BehaviourSubject.value 设置值而不使用 next(),不是不可变的

转载 作者:行者123 更新时间:2023-12-03 01:40:44 24 4
gpt4 key购买 nike

当我测试我的代码时,我不小心遇到了意想不到的突变......或者也许......我只是做错了......

用户

constructor(
public id: number,
public education: Education[]

){}

用户状态服务

private user = new BehaviorSubject<User>(null);

setUser(user:User){
// set by HttpClient or perform an update
this.user.next(user);
}

getUserDetail(){
return this.user.value;
// this.user.getValue(); => tried this as well same thing...
}

updateUserDetail(user:User){
// Maybe perform some check method before the update
this.user.next(user);
// HttpClient to save on db
}

我的组件中有一个表单,用户可以修改自己的数据。所以我的想法是调用 getUserDetail() 并认为返回对象应该是只读的。一旦我设置了新值,我就会 updateUserDetail() 使用 next() 更新可观察值,但我经历了其他情况......

组件

onSubmit(){

let currentUser = this.userService.getUserDetail();

console.log("Original User => ", currentUser); // array(2) see screen shot highlighted

currentUser.educations = this.userForm.value['educations'];

console.log("Modify User => ", currentUser); // array(1)

// this.userService.updateUserDetail(currentUser);

}

enter image description here

currentUser.educations = this.userForm.value['educations']; 我不希望它自动更新可观察值,因为有时我可能需要在之前验证信息做出改变......我怎样才能实现这一目标?

谢谢

最佳答案

我不确定这是否是正确的方法...如果您发现此解决方案是一种不好的做法,请说明问题并提供解决方案。我很高兴更改标记的答案。

但是我就是这么做的。

我基本上有另一个变量来充当与我的主题的联络人。这带来了许多好处,例如在 .next() observable 之前验证数据。

这就是代码的样子

private userSubject = new BehaviorSubject<User>(null);
user$ = this.userSubject.asObservable(); // -> prevent .next() be called on the component
private user: User = null;

setUser(user:User){
this.user = user
// if(user) -> so some check if you desire
this.userSubject.next({...this.user}); // use spread syntax to make a copy so it does not directly refere to this.user
}

// -> Don't need this any more. Just subscribe to user$
// getUserDetail(){
// return this.user.value;
// this.user.getValue(); => tried this as well same thing...
//}

以下解决方案受到本文的启发 https://codeburst.io/javascript-es6-the-spread-syntax-f5c35525f754

扩展语法的文档链接 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

关于Angular rxjs BehaviourSubject.value 设置值而不使用 next(),不是不可变的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51037295/

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