Angular 2:将数据传递给路由? [英] Angular 2: Passing Data to Routes?
问题描述
我正在处理这个 angular2 项目,其中我使用 ROUTER_DIRECTIVES
从一个组件导航到另一个组件.
I am working on this angular2 project in which I am using ROUTER_DIRECTIVES
to navigate from one component to other.
有两个组件.即 PagesComponent
&DesignerComponent
.
There are 2 components. i.e. PagesComponent
& DesignerComponent
.
我想从 PagesComponent 导航到 DesignerComponent.
I want to navigate from PagesComponent to DesignerComponent.
到目前为止它的路由是正确的,但我需要传递 page
对象,以便设计者可以自己加载该页面对象.
So far its routing correctly but I needed to pass page
Object so designer can load that page object in itself.
我尝试使用 RouteParams 但它正在获取页面对象 undefined
.
I tried using RouteParams But its getting page object 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 中,我正在执行以下操作:
In the html, I am doing following:
<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 构造函数中,我完成了以下操作:
In the DesignerComponent constructor I have done the following:
constructor(params: RouteParams) {
this.page = params.get('page');
console.log(this.page);//undefined
}
到目前为止,它正确路由到设计器,但是当我尝试访问设计器中的 page
对象时,它显示 undefined
.有什么解决办法吗?
So far its routing correctly to designer, but when I am trying to access page
Object in designer then its showing undefined
.
Any solutions?
推荐答案
您不能使用路由器参数传递对象,只能传递字符串,因为它需要反映在 URL 中.无论如何,使用共享服务在路由组件之间传递数据可能是更好的方法.
You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.
旧路由器允许传递data
,但新的(RC.1
)路由器还不允许.
The old router allows to pass data
but the new (RC.1
) router doesn't yet.
更新
data
在 RC.4
中重新引入 如何在使用路由时在 Angular 2 组件中传递数据?
这篇关于Angular 2:将数据传递给路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!