简体   繁体   中英

Angular 8: Can't correctly get value from service

I'm having a simple auth service just for testing as I'm learning Angular which sets a localStorage value

GeneralService:

isAuthenticated = new Subject();
autoLogin = new Subject();

AuthenticationService:

if (response.message === 'Logged in') {
    localStorage.setItem('isLoggedIn', '1');
    this.generalS.isAuthenticated.next(true);
  } else {
    this.generalS.isAuthenticated.next(false);
  }

auth component

isAuthSub: Subscription;
// in the submit function ...
this.authS.login(userData);
this.isAuthSub = this.generalS.isAuthenticated.subscribe( (data) => {
  if (data) {
    console.log('Yes');
    this.route.navigate(['recipes']);
  } else {
    console.log('No');
  }
});

In the console I get Yes

In app component

const isLoggedIn = localStorage.getItem('isLoggedIn');
if (!isLoggedIn || isLoggedIn !== '1') {
  this.generalS.autoLogin.next(false);
  this.generalS.isAuthenticated.next(false);
} else {
  console.log('loggenInValue: ' + isLoggedIn);
  this.generalS.autoLogin.next(true);
  this.generalS.isAuthenticated.next(true);
}

And I get this in the console

loggenInValue: 1

So the autoLogin and isAuthenticated subjects should be holding true as a value

I listen th this value in the header component to display or hide the login link but it doesn't log anything

In header component

authSub: Subscription;
isAuthenticated: boolean;
ngOnInit() {
  this.authSub = this.generalS.isAuthenticated.subscribe( (data: boolean) => {
    this.isAuthenticated = data;
    console.log('authenticated: ' + data);
  });
}

I don't get any log from this section. Any ideas regarding solving this issue? [I know I shouldn't check the autologin feature like this but just for testing to check the localStorage value and change other values depending on it]

Since I don't know where the code is at exactly in your authService. I'm assuming you're calling next() before you subscribe, which means there aren't any Subscribers yet. Subjects only emit events to existing Subscribers, not future ones.

You can easily switch to ReplaySubject if your interested in just getting the most recent value on subscription:

isAuthenticated = new ReplaySubject(1);
autoLogin = new ReplaySubject(1);

https://rxjs-dev.firebaseapp.com/api/index/class/ReplaySubject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM