Angular 如何从app.component.html隐藏导航栏并在登录后显示
在我的app.component.html中,我有导航栏和路由器插座。我想从登录页面隐藏导航栏,并在登录后显示它。我使用angular-2/jwt helper检查本地存储中是否有可用的令牌,并根据返回值从登录页面隐藏导航栏。但登录后,导航栏不显示 请帮帮我,先谢谢你Angular 如何从app.component.html隐藏导航栏并在登录后显示,angular,Angular,在我的app.component.html中,我有导航栏和路由器插座。我想从登录页面隐藏导航栏,并在登录后显示它。我使用angular-2/jwt helper检查本地存储中是否有可用的令牌,并根据返回值从登录页面隐藏导航栏。但登录后,导航栏不显示 请帮帮我,先谢谢你 app.component.ts ================ ngOnInit(){ this.authservice.userLoggedIn() } login-service.ts ================
app.component.ts
================
ngOnInit(){
this.authservice.userLoggedIn()
}
login-service.ts
================
从'@angular/Http'导入{Http,Headers};
从“@angular/core”导入{Injectable};
从'angular2 jwt'导入{JwtHelper,tokenNotExpired}
导入'rxjs/add/operator/map';
@可注射()
导出类登录服务{
authToken:任何[];
用户:任何[];
构造函数(私有http:http){}
认证者(用户){
let headers=新的headers();
headers.append('Content-Type','application/json');
返回此.http.post('http://localhost:8080/users/authenticate,用户,{headers:headers})
.map(res=>res.json());
}
storeUserData(令牌、用户){
setItem('id_token',token);
setItem('user',JSON.stringify(user));
this.authToken=token;
this.user=user;
}
userLoggedIn(){
返回tokenNotExpired();
}
}
login.ts
========
onSubmit(表格:NgForm){
常量用户=
{
用户名:form.value.username,
密码:form.value.password
}
this.authservice.authenticateUser(用户).subscribe(数据=>{
if(data.success){
this.invalidlogin=false;
this.authservice.storeUserData(data.token,data.user)
this.authservice.userLoggedIn();
this.router.navigate(['dashboards/dashboard',data.token])
}
否则{
this.invalidlogin=true;
//this.router.navigate(['/']);
}
})
}
app.component.html
==================
对于这种情况,我所做的(在我看来更容易),就是这种结构
AppComponent
LoginComponent
Guarded/
MainView/
MainViewComponent
RandomComponent
/connected
这样,您就可以清楚地区分记录的组件和未记录的组件,并且不必使用条件来显示/隐藏页面中的某些组件 声明一个标志最初将其值设置为false,登录后将其设置为true。
在html设置条件(*ngIf=“flag==true”)。下面是一个例子,这是一个很好的答案。另外,不要忘记添加
{path:'**',redirectTo:'home',pathMatch:'full'}
,这样在任何其他情况下它都会重定向到home(这也应该受到保护。因此,您可以相应地重定向到登录),如果导航栏本身是一个必须在每个页面(组件)中显示的组件,该怎么办@然后你应该将它添加到根组件中,在本例中,根组件就是应用程序组件