subscribe to change of value on object in different component - angularjs

Viewed 31

I am writing an angular app where account service gives method for user to login. When logged in, I want to put on the top bar of the page, welcome xyz. This property will be set in when the user successfully logs in. Until then, the top bar will show nothing (blank). The code I have so far: account.service.ts

private userSubject: BehaviorSubject<IUser>;
public user: Observable<IUser>;

constructor(private http: HttpClient, private appSettingsService: AppSettingsService) {
    super();
    this.userSubject = new BehaviorSubject<IUser>(JSON.parse(localStorage.getItem('user') ?? ''));
    this.user = this.userSubject.asObservable();
}

public get userValue(): IUser {
    return this.userSubject.value;
}

login(email: any, password: any) {
    return this.http.post<IResponseModel>(`${this.appSettingsService.appSettings.apiUrl}user/login`, { email, password })
        .pipe(map(responseModel => {
            if (responseModel.responseCode === 1){
                var user = responseModel.dataSet as IUser;
                localStorage.setItem('user', JSON.stringify(user));
                this.userSubject.next(user);    
            }
            return responseModel;
        }));
}

now I want to listen to change in User object in my app.component.ts (and show in html) I am trying the following code

    private subscriptionAppSettingService: Subscription;
  public user$: Observable<IUser>;
  /**
   *
   */
  constructor(private appSettingsService: AppSettingsService, private accountService: AccountService) {
    this.user$.subscribe(a => {
      a = this.accountService.userValue;
    });      
  }

I see the following error: Cannot read properties of undefined (reading 'subscribe')

the UI has the following code to show the data:

    <span class="navbar-text" style="color:#fff">
  <ng-container >
    <p *ngIf="user$ | async as user">
     here {{ user.fullName }} there
    </p>
  </ng-container>
</span>

What am I missing?

0 Answers
Related