Angular rxjs BehaviorSubject.value设置不带next()的值,不是不可变的

时间:2018-06-26 07:32:02

标签: angular typescript rxjs

在测试代码时,我偶然遇到了意外的突变。...或者也许...我只是做错了所有的事...

用户

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

){}

UserStateService

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'];我不希望它自动更新可观察对象,因为有时在更改之前,我可能需要验证信息...。如何实现此目的?

谢谢

2 个答案:

答案 0 :(得分:0)

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

但这就是我的方法。

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

这是代码的样子

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

答案 1 :(得分:0)

您必须先复制BehaviorSubjects当前值,然后再进行修改。

// e.g. for a Set
const behaviorSubject = new BehaviorSubject<Set<string>>(new Set());
// create copy
const set = new Set(this.behaviorSubject.getValue());
// modify
set.add('item');
// update BehaviorSubject
behaviorSubject.next(set);
// e.g. for an object
const behaviorSubject = new BehaviorSubject<any>({});
// create copy
const value = { ...this.behaviorSubject.getValue() };
// modify
value.a = 'item';
// update BehaviorSubject
behaviorSubject.next(value);