是的,所以我有一个包含以下模板的标题组件(导航栏):
<ng-template [ngIf] = "authService.isAuthenticated()">
<li>
<a routerLink="Landing" class="navbar-brand" (click)="Logout()"><span class="xvrfont">Logout</span><i class="fa fa-sign-in" aria-hidden="true"></i></a>
</li>
<li>
<a routerLink="Profile" class="navbar-brand"><span class="xvrfont">{{authService.getUsername()}}</span><i class="fa fa-user-circle" aria-hidden="true"></i></a>
</li>
</ng-template>
当用户通过身份验证时,导航的这一部分应该是可见的。通过authService查找它。
要检查用户是否经过身份验证,每次路由更改都会运行以下代码:
checkAuthenticated(){
if (localStorage.getItem('token') != null){ this.authenticated = true; }
else { this.authenticated = false; }
console.log(this.authenticated); // for Debugging.
}
NgIf语句调用此方法:
public isAuthenticated(){
return this.authenticated;
}
根据日志,'authenticated' 正确地在true和false之间切换,但是Ngif没有以某种方式响应这些更改。
标题component.ts如下所示:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {AuthService} from "../auth/auth.service";
@Component({
selector: 'app-header',
providers: [AuthService],
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
encapsulation: ViewEncapsulation.None
})
export class HeaderComponent implements OnInit {
constructor(private authService: AuthService) { }
ngOnInit() {
}
Logout(){
this.authService.Logout();
}
}
任何帮助将不胜感激。感谢。
修改
auth.service.ts:
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Router} from "@angular/router";
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
public apiroot = 'http://localhost:3100/';
public loginResponseMessage = '';
public registerResponseMessage = '';
public authenticated = false;
public constructor(private http: HttpClient,
private router: Router) {
}
SignUp(username: string, password: string) {
const User = JSON.stringify({username: username, password: password});
let response: any;
this.http.post(this.apiroot + 'register', User, {headers: new HttpHeaders()
.set('content-type', 'application/json; charset=utf-8')})
.subscribe(res => {
response = res;
this.registerResponseMessage = response.message;
console.log(this.registerResponseMessage);
});
}
Login(username: string, password: string) {
const User = JSON.stringify({username: username, password: password});
let response: any;
this.http.post(this.apiroot + 'authenticate', User, {headers: new HttpHeaders()
.set('content-type', 'application/json; charset=utf-8')})
.subscribe(res => {
response = res;
this.loginResponseMessage = response.message;
if (response.token) {
localStorage.setItem('token', response.token);
this.authenticated = true;
localStorage.setItem('user', response.username);
this.router.navigate(['/']);
}
else{ /* Do Nothing */ }
});
}
Logout(): void{
this.authenticated = false;
localStorage.removeItem('token');
console.log(this.isAuthenticated());
this.router.navigate(['/Landing']);
}
isAuthenticated(){
return this.authenticated;
}
checkAuthenticated(){
if (localStorage.getItem('token') != null){ this.authenticated = true; }
else { this.authenticated = false; }
console.log(this.authenticated); // for Debugging.
}
getUsername(){
var result = localStorage.getItem('user');
return result;
}
}
答案 0 :(得分:4)
一种好方法是通过Observable的反应式编码来共享数据。
在您的服务中,创建一个BehaviorSubject及其Observable:
private _isAuthenticatedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public isAuthenticatedObs: Observable<boolean> = _isAuthenticatedSubject.asObservable();
每次要更新您的值时,请对您的主题next
执行操作:
_isAuthenticatedSubject.next(true); // authenticated
_isAuthenticatedSubject.next(false); // no more
组件方面,只需订阅observable以在本地为每个主题更改设置值:
this.authService.isAuthenticatedObs.subscribe(isAuth => this.isAuth = isAuth);
或使用异步管道在模板中显示值:
<ng-template *ngIf = "authService.isAuthenticatedObs | async">
答案 1 :(得分:3)
问题是您在组件级别提供服务,这意味着,将组件中providers
数组添加到服务的所有组件都将拥有自己的实例服务,所以这根本不是共享服务。您希望拥有单件服务,因此仅在providers
ngModule.
数组中设置服务
也像其他人提到的那样,在模板中调用方法是一个非常糟糕的主意,每次更改检测时都会调用此方法,这通常会影响应用程序的性能。
您可以使用建议的Observable,或者只是在您的服务中使用共享变量。从长远来看,我建议使用Observables,但根据具体情况,共享变量是正常的。以下是两个示例:Passing data into "router-outlet" child components (angular 2)
答案 2 :(得分:2)
模板应该是
<ng-template *ngIf = "authService.isAuthenticated()">