Shlomi Levi
Shlomi Levi

Reputation: 3305

How to change observable complex object?

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

Answers (1)

CozyAzure
CozyAzure

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

Related Questions