Search code examples
javascriptangularangular-ui-routerfrontend

Angular 8, How to navigate to a common page, then navigate to my desired pag?


I am new to front end development. Imagine I have a menu page which has 3 options to navigate to:

  1. Go to Arena.
  2. Go to Dungeon.
  3. Go to Battleground.

But if I click any of these 3 options I will jump to a common page let's say it is character picking:

/characterPicking

If we finished selection and click next, we will navigate to weapon picking:

/weaponPicking

After that finally we will jump to the page we want:

/arena, /dungeon or /battleground

{ path: '', component: MenuComponent },
{ path: 'arena', component: ArenaComponent },
{ path: 'dungeon', component: DungeonComponent},
{ path: 'battleground', component: BattlegroundComponent},
{ path: 'characterPicking', component: CharacterPickingComponent},
{ path: 'weaponPicking', component: WeaponPickingComponent},
{ path: '**', redirectTo: ''},

If above is my rounting path. As you can see, character picking and weapon picking are common components. If I bind the path /characterPicking to the 3 options on menu page. And bind /weaponPicking to the Next Button on characterPicking page. Then how to bind the path for the Next Button on weaponPicking page, how to let weapon picking page know which page should it go next? Arena/Dungeon/BattleGround ?

I hope I explained this clear..


Solution

  • Okay, you have three buttons, but all of them navigate to the same path '/characterPicking'. I think you should manage the button click before navigate and store whitch button the user pressed. Then the user pick his character and navigate to '/weaponPicking' and when he press the last next button you should read the option and navigate to the correct path between 'arena', 'dungeon' or 'battleground'.

    Something like this i think:

    @Component({
      selector: 'app-menu',
      template: `
        <button (click)="go('arena')">Arena</button>
        <button (click)="go('dungeon')">Dungeon</button>
        <button (click)="go('battlegroud')">Battleground</button>
      `,
      styles: []
    })
    export class MenuComponent {
    
      go(where){
        this.stateService.option = where;
        this.router.navigate(['characterPicking'])
      }
    }
    

    And then in your WeaponPickingComponent can do something like this:

    @Component({
      selector: 'app-weapon-picking',
      template: `
        <button (click)="next()">Next</button>
      `,
      styles: []
    })
    export class WeaponPickingComponent {
    
      next(){
        switch(this.stateService.option){
          case 'arena':
            this.router.navigate(['arena']);
            break; 
          case 'dungeon':
            this.router.navigate(['dungeon']);
            break; 
          case 'battlegroud':
            this.router.navigate(['battleground']);
            break; 
        }
      }
    }