我有一个简单的Angular 4项目:
app.component.html
<alert></alert> <-- Alert service
<cat-header></cat-header> <-- Site header with Sign in button
<router-outlet></router-outlet> <-- Main content
<cat-footer></cat-footer> <-- Site footer
按下登录按钮后,将转到登录组件(不同页面)。它使用授权服务来检查数据库中的用户,如果已建立,则将其存储在
中localStorage.setItem('currentUser', JSON.stringify(user));
成功登录登录组件后,使用
导航到主页面this.router.navigate([this.returnUrl]);
问题是导航完成后没有Header Component更新(没有调用Constructor和ngOnInit代码)。当我在初始导航后在浏览器中按Ctrl + F5时,标题组件会更新。
我试图通过互联网搜索此案例并创建了一些复杂的解决方案,例如使用带有页面重新加载的发射器或虚拟路径。但解决这么简单的任务看起来非常复杂。
这是我的标题组件:
export class HeaderComponent implements OnInit {
currentUser: User;
constructor(private activatedRoute: ActivatedRoute, private userService: UserService) {
this.activatedRoute.params.subscribe(data => {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
});
}
ngOnInit() {
}
}
以下是带有登录按钮的标题组件模板中的代码:
<a *ngIf="currentUser; else notLogedIn" href="javascript: void(0);" [routerLink]="['/login']">Log off</a>
<ng-template #notLogedIn><a href="javascript: void(0);" [routerLink]="['/login']">Log in</a>
所以此时它只显示不同的链接文字。
这种逻辑的可视化:
答案 0 :(得分:2)
我尝试过不同的方法,从我的角度来看,这是最简单的解决方案。
我创建了一个服务来检查当前用户状态:
double remainingDays = (dateEnding - dateStarting).TotalDays;
richTextBox3.Text = remainingDays.ToString();
if (remainingDays <= 0)
{
MessageBox.Show("Warning !!!!!");
}
并从我的标题组件订阅此服务:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class CurrentUserService {
itemValue = new Subject<string>();
set currentUser(user) {
this.itemValue.next(user);
localStorage.setItem('currentUser', user);
}
get currentUser() {
return localStorage.getItem('currentUser');
}
}
它就像一个魅力!
答案 1 :(得分:0)
提供服务以了解用户是否已登录
<cat-header *ngIf="userService.isLoggedIn()"></cat-header>
isLoggedIn(){
return true/ false ;
}
答案 2 :(得分:0)
另一种方式 我知道如果您不想解析这是一个古老的问题,另一种方法可以是:
在Authentication.ts
export class AuthService {
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
constructor(private http: HttpClient)
{
this.currentUserSubject = null;
this.currentUser = null;
const currentUser = localStorage.getItem('currentUser');
if (currentUser !== 'undefined') {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(currentUser));
this.currentUser = this.currentUserSubject.asObservable();
}
}
您可以像下面这样在组件构造函数上调用它:
constructor(
private router: Router,
private authenticationService: AuthService)
{
this.authenticationService.currentUser.subscribe(currentUser => {
this.currentUser = currentUser;
});
}