[英]How can I fire an app-wide event in Angular2 or observe a global variable
我有以下架构:
Navbar是一个组件:
loggedIn = false;
constructor(private authService: AuthService) {
this.loggedIn = authService.isAuthenticated();
}
根据变量显示不同的链接
authService中的方法:
isAuthenticated() : boolean {
return tokenNotExpired();
}
authenticate(email: string, password: string) : Promise<void> {
const headers = new Headers({
'Content-Type': 'application/json'});
const body = JSON.stringify({ email, password });
return this.http.post(`${apiUrl}/auth/login`, body, { headers })
.toPromise()
.then(response => {
const data = response.json();
this.user = data.user;
localStorage.setItem('id_token',data.token);
});
}
当isAuthenticated()返回另一个值时,我希望在navbar中收到通知。
我应该在AuthService中使用可观察的值而不是仅检查有效令牌吗? 我应该在身份验证方法的成功中发出事件吗? 我只能通过@input
找到有关父子事件emmiters的信息。
注意:我正在使用angular2-jwt,并且从auth.guard为受保护路由调用isAuthenticated()方法。
您绝对应该在AuthService中使用Observable主题。 从angular.io看一下这个链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.