在Angular 2中调用组件刷新 [英] Invoke component refresh in Angular 2
问题描述
我正在尝试实现一个导航栏,该导航栏根据用户是否登录来显示不同的链接.
I am trying to implement a navbar that shows different links based on whether or not a user is logged-in.
我正在使用提供tokenNotExpired()
功能的angular2-jwt
库.
I am using the angular2-jwt
library which provides the tokenNotExpired()
function.
我有2条路线,/home
和/login
.我有一个导航栏组件,它位于<router-outlet>
之外,这意味着它仅被初始化一次,而不是每次路径更改时都被初始化.
I have 2 routes, /home
and /login
. I have a navbar component which is outside of the <router-outlet>
, which means it is initialized only once and not every time the route changes.
成功登录后,我正在调用router.navigate(['/home])
.主页和登录名都可以检查用户是否已在各自的ngOnInit()
功能中登录.因此,home组件能够检测到已登录的用户.
After successful login, I am invoking router.navigate(['/home])
. The home and login both have checks for if a user is logged-in in their respective ngOnInit()
functions. The home component is therefore able to detect the logged-in user.
但是,由于没有通知登录,我无法更新导航栏.
However, I am unable to update the navbar since it is not informed of the login.
任何人都可以告诉我实施此更改检测的正确方法吗?
Could anyone please tell me the correct way to implement this change detection?
谢谢.
推荐答案
通过服务公开登录状态
@Injectable()
export class UserAuthService{
userLoggedIn : bool = false;
//call this function when login status changes
changeLoginStatus(status: bool){
this.userLoggedIn = status;
}
}
使您的服务单调
@NgModule({
declarations: [
NavbarComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing,
],
providers: [UserAuthService], // <-- Provide your service here
bootstrap: [AppComponent]
})
export class AppModule { }
在导航栏中使用您的服务
user your service in your navbar
import { UserAuthService } from 'path/to/service';
export class NavbarComponent {
constructor(private authService: UserAuthService ) { } // <-- inject service
ngOnInit() { }
}
因此您可以使用服务来更改模板.
so you can change your template using service.
<div [hidden]="!authService.userLoggedIn"><a routerLink="/login">login</a></div>
登录状态更改后,
调用服务的changeLoginStatus
功能.
call changeLoginStatus
function of the service when login status changes.
这篇关于在Angular 2中调用组件刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!