0

I would like to save user data after login in an observable and retrieve the data later in the profile page. I have a simple user.service.ts

  @Injectable()
export class UserService {
  private _user: BehaviorSubject<IRegisterUser> = new BehaviorSubject<IRegisterUser>(null);
  public user$: Observable<IRegisterUser> = this._user.asObservable();

  constructor(public afAuth: AngularFireAuth) {}

  public setUser(user) {
    this._user.next(user)
  }

which successfully updates the behavior subject.

Later I try to have access of the observable in profile.page.ts

export class ProfilePage implements OnInit {

  constructor(public userSrv: UserService) { }

  ngOnInit() {
   this.userSrv.user$.subscribe(resp=> {
     console.log(resp)
   })

  }

}

But my response is null

I have put the user.service.ts in the providers of app.module and profile.module but I probably miss something else.

sniperalex117
  • 79
  • 3
  • 9
  • Did you push a new `user` to the observable? If not you will receive the default value `null`. Now if you were to push a new user to the observable after the subscription, they will be reflected in the `profile.page`. – ruth May 22 '20 at 10:17
  • What I did is `this._user.asObservable();` and add the value to the behavior subject. Where should I push the value to the observable? – sniperalex117 May 22 '20 at 10:22
  • When the user is logged in I call the method `setUser(user)` and I successfully update the behavior subject. I saw it on debug mode. The problem is that my subscription in `profile.page.ts` doesn't work for some reason. – sniperalex117 May 22 '20 at 10:29

1 Answers1

1

I have put the user.service.ts in the providers of app.module and profile.module but I probably miss something else.

There is a problem, remove UserService from profile.module providers. Now profile.module have his own provider of UserService instead of using global provider.

izmaylovdev
  • 1,828
  • 8
  • 16