Angular 2:将数据传递给路由?

新手上路,请多包涵

我正在研究这个 angular2 项目,在该项目中我使用 ROUTER_DIRECTIVES 从一个组件导航到另一个组件。

有2个组件。即 PagesComponent & DesignerComponent

我想从 PagesComponent 导航到 DesignerComponent。

到目前为止,它的路由正确,但我需要传递 page 对象,以便设计人员可以自行加载该页面对象。

我尝试使用 RouteParams 但它正在获取页面对象 undefined

下面是我的代码:

pages.component.ts

 import {Component, OnInit ,Input} from 'angular2/core';
import { GlobalObjectsService} from './../../shared/services/global/global.objects.service';
import { ROUTER_DIRECTIVES, RouteConfig } from 'angular2/router';
import { DesignerComponent } from './../../designer/designer.component';
import {RouteParams} from 'angular2/router';

@Component({
    selector: 'pages',
    directives:[ROUTER_DIRECTIVES,],
    templateUrl: 'app/project-manager/pages/pages.component.html'
})
@RouteConfig([
  { path: '/',name: 'Designer',component: DesignerComponent }
])

export class PagesComponent implements OnInit {
@Input() pages:any;
public selectedWorkspace:any;
constructor(private globalObjectsService:GlobalObjectsService) {
    this.selectedWorkspace=this.globalObjectsService.selectedWorkspace;
}
ngOnInit() { }
}

在 html 中,我正在执行以下操作:

 <scrollable height="300" class="list-group" style="overflow-y: auto; width: auto; height: 200px;" *ngFor="#page of pages">
    {{page.name}}<a [routerLink]="['Designer',{page: page}]" title="Page Designer"><i class="fa fa-edit"></i></a>
</scrollable>

在 DesignerComponent 构造函数中,我完成了以下操作:

 constructor(params: RouteParams) {
    this.page = params.get('page');
    console.log(this.page);//undefined
}

到目前为止,它正确地路由到了设计器,但是当我尝试访问 page 设计器中的对象时,它会显示 undefined 。有什么解决办法吗?

原文由 Bhushan Gadekar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 368
1 个回答

您不能使用路由器参数传递对象,只能传递字符串,因为它需要反映在 URL 中。无论如何,使用共享服务在路由组件之间传递数据可能是一种更好的方法。

旧路由器允许通过 data 但新的( RC.1 )路由器还没有。

更新

dataRC.4 如何在使用路由时在 Angular 2 组件中传递数据?

原文由 Günter Zöchbauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题