gpt4 book ai didi

angular - 在路由 Angular 4 中传递多个参数

转载 作者:太空狗 更新时间:2023-10-29 17:00:24 25 4
gpt4 key购买 nike

你好,我想通过 Angular 4 中的路由传递一些参数

应用路由.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 {

}

在组件StartGameComponent

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

在组件 GameComponent

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

});

在 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>

它会抛出一个错误

Cannot match any routes. URL Segment: 'game;width=10;height=10'

最佳答案

您将必需路由参数的语法与可选路由参数混合在一起。

Angular 提供了三种路由参数:1) 必需的参数。2) 可选参数。3) 查询参数。

必填参数为必填值,比如显示详情页的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

关于angular - 在路由 Angular 4 中传递多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43746795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com