Invoke component refresh in Angular 2

2019-02-15 13:57发布

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

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

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.

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?

Thanks.

1条回答
贪生不怕死
2楼-- · 2019-02-15 14:38

Expose login status via service

@Injectable()
export class UserAuthService{
    userLoggedIn : bool = false;

    //call this function when login status changes
    changeLoginStatus(status: bool){
        this.userLoggedIn = status;
    }
}

make your service singleton

@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> 

call changeLoginStatus function of the service when login status changes.

查看更多
登录 后发表回答