在 Angular 2 中调用组件刷新 [英] Invoke component refresh in Angular 2

查看:65
本文介绍了在 Angular 2 中调用组件刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个导航栏,根据用户是否登录显示不同的链接.

I am trying to implement a navbar that shows different links based on whether or not a user is logged-in.

我正在使用 angular2-jwt 库,它提供了 tokenNotExpired() 函数.

I am using the angular2-jwt library which provides the tokenNotExpired() function.

我有 2 条路线,/home/login.我有一个位于 之外的导航栏组件,这意味着它只初始化一次,而不是每次路由更改时.

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]).home 和 login 都在各自的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆