2

I'm trying to implement an auto-login system where I save the login data to local storage so that on refresh I fetch the data from local storage.

When I fetch the data from local storage I use Subject to emit that data so that in the header component I subscribe for the data and maintain the application state on refresh.

Now on refresh, my autologin function is getting called but Subscription is not calling in the header component

AuthService Code

    autoLogin(){
    const userdata: {
        email:string;
        id: string;
        _token:string;
        _tokenExpairDate:Date;
    }=JSON.parse(localStorage.getItem('userData'));

    if(!userdata){
      return;
    }

    console.log("Auto Login Call");
    
    const loadedData=new User
    (
      userdata.email,
      userdata.id,
      userdata._token,
      new Date
      (
        userdata._tokenExpairDate
      )
    );

    if(loadedData.token){
      console.log(loadedData);
      console.log("data Emmit");
      this.user.next(loadedData);
    }
    else{
      console.log("data Not Emmit");
    }
 }

header component code

ngOnInit(){
    this.userSub=this.auth.user.subscribe(user=>{
      console.log("Subscription Call");
      this.isLogin=!user? false:true;
    })
  }
8
  • could you also provide code where you "register" your AuthService in modules
    – Andrei
    May 4, 2021 at 15:17
  • @Injectable({ providedIn: 'root' }) export class AuthServiceService {
    – Taqi Arzoo
    May 4, 2021 at 15:19
  • do you also put it in providers section anywhere?
    – Andrei
    May 4, 2021 at 15:20
  • Now no but I try that also in app.modules
    – Taqi Arzoo
    May 4, 2021 at 15:21
  • is console.log("Subscription Call"); being executed?
    – Andrei
    May 4, 2021 at 15:22

1 Answer 1

3

Am not sure how you are actually setting the observable, but this might help you.

// In user.modal.ts export a interface for the user
// You need to define this so that you dont need to repeat your code

export interface User {
    email:string;
    id: string;
    _token:string;
    _tokenExpairDate:Date;
}
************************************
// In your service file, do this: 

import { User } from './user.modal.ts';

let initialUserDetails: User = {};

private userDetailsSource: BehaviorSubject<User> = new BehaviorSubject<User>(this.initialUserDetails);

public userDetailsObservable: Observable<User> = this.userDetailsSource.asObservable();

setUserDetails(userDetails: User) {
    this.userDetailsSource.next(userDetails);
}

getUserDetails(): Observable<User> {
    return this.userDetailsObservable;
}

********************************
// In your component.ts file, whenever you want to set the details: 

if (loadedData.token) {
    console.log(loadedData);
    console.log("data Emmit");
    this.user.next(loadedData); // Dont do this:

    this.yourServiceName.setUserDetails(loadedData); // Do this;
}


// Whenever you want to get the details of the Observable, you can do this: 

this.yourServiceName.getUserDetails().subscribe(subscribedData => {
    console.log('Latest Observable Data =>', subscribedData);
})

1
  • Note that using a BehaviorSubject, when you'll subscribe to it, you may receive the init value (here {}), and then receive a second event with the real data. So you should add a check in the subscribe. That's the reason why we often use null as init value, so it is easy to ignore.
    – Random
    May 4, 2021 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.