Home > Blockchain >  can't pas values to a angular observable
can't pas values to a angular observable

Time:10-05

i am trying to use a observable to see if the user data is changed and if so i want to update the router.but the problem is every time i update the user the subscription is not activated its only activated on initialization.

i get the user from auth0 subscription and then pas it on to the currentUser

userservice.ts

private currentUser: userDto = {}
public currentUserObserv: Observable<userDto> = of(this.currentUser)

routingService.ts

  private userSubscription = this.userService.currentUserObserv.subscribe(
user => this.handleRoles(user)

)

CodePudding user response:

of() creates a cold observable that does nothing.

What you want is a BehaviorSubject.

private _currentUser = new BehaviorSubject<userDto>({});
public currentUser$ = this._currentUser.asObservable();
get currentUser() { return this._currentUser.value; }
setCurrentUser(user: userDto) { this._currentUser.next(user); }

CodePudding user response:

You need to use a Subject or BehaviorSubject (which keeps the current value) for this purpose.

private currentUserSubject: Subject<userDto> = new Subject<userDto>();
public currentUser$: Observable<userDto> = this.currentUserSubject.asObservable();
    
emitNewUser(user: userDto): void {
  this.currentUserSubject.next(user);
}
  • Related