Passing multiple parameters to angular 4 route

Hello, I want to pass some routing parameters in angular 4

application-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { StartGameComponent } from './start-game/start-game.component';
import { GameComponent } from './game/game.component';


const appRoutes: Routes = [
  { path: '', redirectTo: '/first', pathMatch: 'full' },
  { path: 'startGame', component: StartGameComponent },
  {path: 'game/:width/:height',component: GameComponent
  }

];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule {

}

in the component StartGameComponent

      goToGameComponent(width:string,height:string){
      this.router.navigate(['game', {width:width,height:height}]);
}

in component GameComponent

 ngOnInit() {
        this.route.params.forEach((urlParams) => {
          this.width= urlParams['width'];
          this.height=urlParams['height'];

        });

in app.component.html

<div>
  <md-toolbar color="primary">
    <span>MineSweeper Wix</span>

  </md-toolbar>
  <router-outlet></router-outlet>

  <span class="done">
    <button md-fab>
      <md-icon>check circle</md-icon>
    </button>
  </span>
</div>

he gives me an error

Unable to map routes. URL segment: 'game; width = 10; height = 10 '

+11
source share
2 answers

You mix the syntax of the required routing parameters with the optional routing parameters.

Angular provides three types of route parameters: 1) Required parameters. 2) Optional parameters. 3) Request parameters.

, Id . ?

- , , , , .

, . , - , .

. ( "" )

:

: this.router.navigate(['game', width, height]);

: this.router.navigate(['game', {width:width,height:height}]);

: this.router.navigate(['game', { queryParams: {width:width, height:height}}])

, : https://app.pluralsight.com/library/courses/angular-routing/table-of-contents

+34

- , . , :

,

const arrayItem = [{ source: "external" }, { fileFiler: "File Name 1" }];
const queryParams = arrayItem.reduce((arrObj, item) => Object.assign(arrObj, item, {}));  // this will convert into single object. 

// Output: {source: "external", fileFiler: "File Name 1"}
Hide result

, , , :

this.router.navigate([], { relativeTo: this.activatedRoute, queryParams });

!

0

Source: https://habr.com/ru/post/1676196/


All Articles