首页 > 解决方案 > Angular Observer 用户是否登录

问题描述

我的 login.component 正在使用令牌设置本地存储项。我希望我的 nav.component 始终了解它并在令牌存在或删除时做出反应,并且我希望我的 Auth 持有 Observable。我希望我的 nav.component 订阅 Observable。我想我快到了,但需要一些最后的指导。截至目前,它不会改变我的导航中的任何属性。

截至目前,我无法观察到对本地存储所做的任何更改。它总是返回假。我可以将loggedIn设置为true,我的导航会对此做出反应,所以我想这与Auth中的Observable有关。

这是我的 app.component 包含导航。

<app-nav></app-nav>
<div> 
    <router-outlet></router-outlet>
</div>

我的导航组件:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})

export class NavComponent implements OnInit {

  public isLoggedIn: Boolean;

  constructor(
    private auth: AuthService, private router: Router
    ) {}

  ngOnInit() {
    this.auth.isLoggedIn().subscribe(
      mes =>{
        this.isLoggedIn = mes;
      }
    );
  }
  handleAction(){
    console.log(this.isLoggedIn);
  }
  logoutUser(){
    this.auth.logoutUser();
  }
}

还有我的 auth.service:

import { Injectable, EventEmitter, Output } from '@angular/core';
import { HttpClient, HttpHeaderResponse, HttpErrorResponse} from '@angular/common/http';
import {Subject, Observable, EMPTY, throwError,} from 'rxjs';
import { Router } from '@angular/router';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class AuthService {  
  private apiroot = "My api root";
  public loggedIn = false;
  logger = new Subject<boolean>();

  constructor(
    private http: HttpClient,
    private router : Router
  ) { }
  isLoggedIn(): Observable<boolean> {
    return this.logger.asObservable();
  }
  loggedInStatus(){
    //Used for guards
    return !!localStorage.getItem('token');
  }
  registerUser(user){
    return this.http.post<any>(this.apiroot + "register", user)
      .pipe(catchError(this.errorHandler))
  }
  resetPassword(user){
    return this.http.post<any>(this.apiroot + 'resetpassword', user)
      .pipe(catchError(this.errorHandler))
  }
  loginUser(user){
    // this.loggedIn = true;
    this.logger.next(this.loggedIn);
    return this.http.post<any>(this.apiroot + "login", user)
  }
  logoutUser(){
    localStorage.removeItem('token');
    this.loggedIn = false;
    this.logger.next(this.loggedIn);
    this.router.navigate(['/']);
  }
}

标签: angularauthenticationlocal-storage

解决方案


推荐阅读