【问题标题】:Anguar2 routerLink returning inaccurate URLAnguar2 routerLink 返回不准确的 URL
【发布时间】:2017-04-20 03:12:41
【问题描述】:

我正在尝试实现 angular2 路由器,并使用像 '/detail/:index' 这样的 URL 模式来传递像 ':detail/1234' 这样的东西。但它得到“someDomain/detail/%3AitemIndex;itemIndex=123”,这意味着“/detail/:itemIndex;itemIndex=123”。如何解决此问题并获得“/detail/123”或“/detail/itemIndex = 123”的预期结果并摆脱“:itemIndex;”并用斜线替换它(请忽略我的错别字)

“app.routes.ts”

 export const rootRouterConfig: Routes = [
  { path: '', redirectTo: 'SomeHomeComponent', pathMatch: 'full' },
  { path: 'home', component: SomeHomeComponent },
  { path: 'detail/:itemIndex', component: SomeDetailComponent }];

“list.component.html”

  <a *ngFor="let item of items; let i = index" 
[routerLink]="['/detail/:itemIndex', { itemIndex: i }]"> 
{ item.name }
</a>

“SomeDetail.Component.ts”

import { ActivatedRoute } from '@angular/router';

export class SomeDetailComponent {
  private itemIndex:string;

  constructor(private  route: ActivatedRoute){

  }
  ngOnInit () {

    this.route.params.subscribe(params => { this.itemIndex = params['itemIndex'];
    });
}
}

【问题讨论】:

    标签: angular angular2-routing angular2-directives angular2-services typescript2.0


    【解决方案1】:

    使用:

    “list.component.html”

    <a *ngFor="let item of items; let i = index" 
        [routerLink]="['/detail', i]"> 
        {{ item.name }}
    </a>
    

    希望这会有所帮助..

    【讨论】:

      【解决方案2】:

      RouterLink 文档中所述,您可以将多个变量与多个参数连接起来。

      您的代码现在将变为:

      <a *ngFor="let item of items; let i = index" [routerLink]="['/detail/', i ]"> 
          {{ item.name }}
      </a>
      

      【讨论】:

        【解决方案3】:

        PS:只是建议

        在使用 *ngFor 或类似的东西绑定时最好使用elvis ? 运算符,它可以防止这样的应用程序出错或崩溃,

         <a *ngFor="let item of items; let i = index" 
        [routerLink]="['/detail/:itemIndex', { itemIndex: i }]"> 
        {{ item?.name }}
        </a>
        

        这里我用过{{item?.name}}

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-11
          • 2014-01-27
          相关资源
          最近更新 更多