Invoke component refresh in Angular 2

ぃ、小莉子 提交于 2019-12-19 04:25:10

问题


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:


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.



来源:https://stackoverflow.com/questions/40213694/invoke-component-refresh-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!