angular - 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(['/']);
}
}
解决方案
推荐阅读
- .htaccess - 将域别名重定向到主域页面?
- angular - ngRx Store - Reducer 返回未定义 - store.select() 未定义
- python - 是否有可能在 ffmpeg 命令中引发错误?
- css - 绝对元素的水平定位
- netsuite - 以编程方式远程执行 SuiteScript
- node.js - Wix 和 Squarespace 如何能够为不同的域生成和提供 SSL?
- git - 'git diff' 的简写是什么,如果有的话?
- database - 如何创建从 SQL Server DB 到 MongoDB 或 Cassandra 的数据管道?
- angular - Angular 从 7 更新到 8,我卡住了 angular-i18next
- ruby-on-rails - 如何使用嵌套的 json 对象创建 json 响应?