1

I am using a subject in rxjs to pass data from my login component to the user-profile component but what happens is in my login component I call the sendUser method in the login component then in the user-profile component I subscribe to the observable but the currentUserObj value is undefined when I console.log the value. Can someone please help me since I've been trying to fix this for hours? Thanks.

auth.service.ts

  private userSource = new Subject<User>();
  currentUser$ = this.userSource.asObservable();

  sendUser(user: any) {
    this.userSource.next(user);
  }

login.component.ts

loginUser() {
    this.user = {
      email: this.email,
      password: this.password,
    };
    this._auth.loginUser(this.user).subscribe(
      (res) => {
        this.token = res.access_token;
        this.user = res.user;
        localStorage.setItem('token', this.token);
        this._auth.sendUser(this.user); // This is where I use the send user function in my auth service
        this._router.navigate(['/profile']);
      },
      (err) => {
        this.errorMessage = err.message;
      }
    );
  }

user-profile.component.ts

  constructor(private _auth: AuthService) {}

  currentUserObj: {};

  ngOnInit(): void {
    this._auth.currentUser$.subscribe((user) => {
      this.currentUserObj = user;
    });
    console.log(this.currentUserObj);
  }
lizardcoder
  • 336
  • 3
  • 6

1 Answers1

2

I think you are getting this behavior because Subject gives only data emmited by source after your subsription to it. If you want no undefined inside ngOnIt() after subscribing to the subject, you need to use BehaviorSubject to which you need to assign some initial value while making it which it immediately emits, so this type of subject returns the last emitted data from the source when you subscribe to it. This last emitted value may be the inital value (that you assigned while making Behaviour subject) or the data emitted later depending on when you subscribe to it.
so in your auth.service.ts, you can use Behaviorsubject like this

  private userSource = new BehaviorSubject<User>(user); //pass either a dummy user or current user in the constructor argument of BehaviorSubject
  currentUser$ = this.userSource.asObservable();

  sendUser(user: any) {
    this.userSource.next(user);
  }

so after using behaviour subject what happens now is that when your user-profile component loads and you subscribe to the subject in the auth.service.ts after component is made in ngOnInit(), you can get the last emitted data, which you emitted after authenticating the user in your login.component.ts and then routing to profile component;
please refer this for more info What is the difference between Subject and BehaviorSubject?

mss
  • 1,423
  • 2
  • 9
  • 18