Invoke component refresh in Angular 2

后端 未结 1 1291
粉色の甜心
粉色の甜心 2021-01-15 13:11

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 prov

相关标签:
1条回答
  • 2021-01-15 13:57

    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.

    0 讨论(0)
提交回复
热议问题