Reputation: 3305
In rxjs I want to change property in complex object BUT CHANGE NOTHING ELSE.
For example:
I have User Class:
class User {
constructor(
public name: string,
public role: string
) { }
}
My Service:
@Injectable()
export class AuthService {
user: BehaviorSubject<User>;
constructor() {
this.user = new BehaviorSubject(
new User('wizardnet', 'admin')
);
}
setRole(role) {
// change ONLY the Role property of this.user ???????
// subscribe then clone the object and then call next() ??
}
}
How to do that?
Upvotes: 1
Views: 1126
Reputation: 8468
Actually you got it all correct except that you don't need to subscribe to get the value of the user in your service. You can just use .value
:
@Injectable()
export class AuthService {
user: BehaviorSubject<User>;
constructor() {
this.user = new BehaviorSubject(
new User('wizardnet', 'admin')
);
}
setRole(role) {
const updateUser = Object.assign(this.user.value, {role: role});
this.user.next(updateUser);
return this.user.asObservable();
}
}
Upvotes: 1