Search code examples
angularangular-route-guards

Show initial user setup component only on first login


I have 2 components intial-settings and app-navbar inside my app.component.html:

<initial-settings *ngIf="!userFloor"></initial-settings> <app-navbar *ngIf="userFloor"></app-navbar>

And my app.component.ts:

export class AppComponent {
  public userFloor;

  constructor(private userFloorService: UserFloorService){}

  ngOnInit(){
    this.userFloorService.getJSON().subscribe(
      data => this.userFloor = data);
  }
}

I want to show intial-settings component only on first user login, so the user can setup some things. On all of the next user logins, the app should show the second app-navbar component right away, beacuse user has alerady set up those required things, and they are stored in database.

So, i use service to get the data. If the data is empty, which means user is loging in for the first time, show the initial-setting component. After the data is saved, redirect to the app-navbar component. If the data is not empty show the app-navbar component.

My question is, how to implement this logic, that means which is the best way to show/hide these 2 components and how to redirect from the intial-settings component to the app-navbar component after user saves the required setup data.

I think i need to use router with router guards but i didn't find any example of this use case, which i would understand clearly enough. I am new to Angular, thanks!


Solution

  • using angular routing You can create a function for This logic ! like...

    app.component.ts

    import { Router, ActivatedRoute } from '@angular/router';
    export class AppComponent {
          public userFloor;
        
          constructor(private userFloorService: UserFloorService, private router: Router,){}
        
          ngOnInit(){
            this.userFloorService.getJSON().subscribe(
              (data) =>{ 
              if(data.length){
                this.router.navigate(['/PAGE-PATH']);
              }else {
                this.router.navigate(['/PAGE-PATH']);
               }
              });
             }
           }
    

    hope it will usefull for all !