簡體   English   中英

Angular 8:無法從服務中正確獲取價值

[英]Angular 8: Can't correctly get value from service

我有一個簡單的身份驗證服務,僅用於測試,因為我正在學習設置 localStorage 值的 Angular

一般服務:

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

認證服務:

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

授權組件

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');
  }
});

在控制台中我得到Yes

在應用組件中

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);
}

我在控制台中得到了這個

loggenInValue: 1

所以 autoLogin 和 isAuthenticated 主題應該保持true作為一個值

我在標頭組件中收聽此值以顯示或隱藏login鏈接,但它不記錄任何內容

在標頭組件中

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

我沒有從這個部分得到任何日志。 關於解決這個問題的任何想法? [我知道我不應該像這樣檢查自動登錄功能,而只是為了測試以檢查 localStorage 值並根據它更改其他值]

因為我不知道代碼在你的 authService 中的確切位置。 我假設您在訂閱之前調用 next(),這意味着還沒有任何訂閱者。 主題只向現有的訂閱者發出事件,而不是未來的訂閱者。

如果您只想獲取訂閱的最新值,您可以輕松切換到 ReplaySubject:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM