我的login.component正在设置带有令牌的localstorage项目。我希望nav.component始终了解它,并在令牌存在或删除时做出反应,并且我希望Auth保留Observable。我希望我的nav.component订阅Observable。我认为我快到了,但是需要最后的指导。到目前为止,它不会更改导航中的任何属性。
到目前为止,我还无法观察到对本地存储所做的任何更改。它总是返回false。我可以将loginIn设置为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();
}
}
我的身份验证服务
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(['/']);
}
}