angularionic-frameworkionic4injectable

Save data in observable (ionic 4)


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.


Solution

  • 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.