【问题标题】:Router not working in angular2-rc1路由器在 angular2-rc1 中不起作用
【发布时间】:2016-05-26 10:31:45
【问题描述】:

我正在尝试在 angular2 中使用路由器。我使用一个链接重定向到DesignerComponent 并将page._id 作为RouteParams 传递。 该代码在 angular2-beta 中正常工作。 以下是我的代码:

pages.component.ts

import { Component, OnInit ,Input} from '@angular/core';
import {SearchPipe} from './../../shared/pipes/search-pipe.pipe';
import { GlobalObjectsService} from './../../shared/services/global/global-objects.service';
import { Router,Routes , ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from '@angular/router';
import { DesignerComponent } from './../../+designer/designer.component';

@Component({
  moduleId: module.id,
  selector: 'app-pages',
  pipes: [SearchPipe],
  directives: [ROUTER_DIRECTIVES],
  providers: [ROUTER_PROVIDERS],
  templateUrl: 'pages.component.html',
  styleUrls: ['pages.component.css']
})
@Routes([  
  {path: '/designer', component: DesignerComponent}
])
export class PagesComponent implements OnInit {

  @Input() pages:any;    
  constructor(private router:Router) {

  }
  ngOnInit() { }
  selectPage(page_id:string){                    
  }  

}

在我看来,我做了以下事情:

<div [routerLink]="['Designer',{page_id: page._id}]" class="btn btn-xs btn-success" title="Design Page">
    <i class="fa fa-eye fa-fw"></i>
</div>

但它向我显示以下错误:

Argument of type '{ path: string; name: string; component: typeof DesignerComponent; }[]' is not assignable to parameter of type 'RouteMetadata[]'

我只想在点击以 page_id 作为参数的链接时重定向到DesignerComponent

任何输入?

【问题讨论】:

    标签: javascript typescript angular angular2-routing


    【解决方案1】:

    在路由元数据中添加参数:

    @Routes([  
      {path: '/designer/:page_id', component: DesignerComponent}
    ])
    

    在routerLink中直接使用page._id,不带对象:

    [routerLink]="['/designer',page._id]"
    

    更新

    从组件访问参数值:

    constructor(curr: RouteSegment) {
            let itemID = curr.getParam("page_id");
        }
    

    【讨论】:

    • 但是由于 routeParams 不起作用,我如何访问设计器组件中的 page._id?
    • 我在 routerLink 中有错字。而不是 Designer 应该使用 /designer
    • 这意味着我们必须在各处使用相同的名称page_id,即在发送参数时和接收端对吗?
    【解决方案2】:

    新的RouteDefinition 没有name 属性。因此,只需将其删除即可:

    @Routes([  
      {path: '/designer', component: DesignerComponent}
    ])
    

    视图将是:

    &lt;div [routerLink]="['/designer',{page_id: page._id}]" ... &gt;

    <a [routerLink]="['/designer',{page_id: page._id}]"  ... >
    

    【讨论】:

    • 试过了。它显示错误:Can't bind to 'routerLink' since it isn't a known native property
    • 对此有何意见?
    • 你有 吗?抱歉,我现在正在手机上写字。 .给我几分钟
    • 它有效..但我需要使用&lt;a [routerLink]="['/designer',{page_id: page._id}]"&lt;/a&gt; 而不是&lt;div [routerLink]="['/designer',{page_id: page._id}]"&lt;/div&gt; ..有什么原因吗?
    • @BhushanGadekar 这实际上是有道理的,因为如果您查看the code of routerLink。您可以看到它绑定到href 属性,该属性在 div 上不可用。
    猜你喜欢
    • 1970-01-01
    • 2016-07-11
    • 2017-03-25
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2016-09-20
    相关资源
    最近更新 更多