【问题标题】:Angular 2: Passing Data to Routes?Angular 2:将数据传递给路由?
【发布时间】:2016-09-06 13:43:02
【问题描述】:

我正在处理这个 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。 有什么解决办法吗?

【问题讨论】:

  • ROUTER_DIRECTIVES 听起来你使用的是黑暗时代的 Angular 版本;-)
  • 你也可以召唤这种“撒旦噱头”:导航前this.router['arbitraryData'] = data,最后导航目标let arbitraryData = this.router['arbitraryData']。我会把这个留在这里,以防我忘记并最终再次找到这个页面,以防万一

标签: javascript typescript angular angular2-routing


【解决方案1】:

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

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

更新

dataRC.4中重新引入How do I pass data in Angular 2 components while using Routing?

【讨论】:

  • 那么在目前的情况下看这个项目可以做什么?
  • 您在父组件中提供服务并将其注入到两个路由组件中。当您从一个组件设置属性时,另一个组件可以读取该属性。 angular.io/docs/ts/latest/cookbook/…
  • 我已经将这种方法用于不同的目的。我在想如果我可以将 page_id 作为字符串传递,那么它也可以。但它也将 page_id 设为 null。
  • 如果它是一个字符串,它应该可以工作。一个 plunker 会很好地调试这个问题。
【解决方案2】:

角度变化 2.1.0

在something.module.ts中

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
const routes = [
  {
    path: '',
    component: BlogComponent
  },
  {
    path: 'add',
    component: AddComponent
  },
  {
    path: 'edit/:id',
    component: EditComponent,
    data: {
      type: 'edit'
    }
  }

];
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
    MaterialModule.forRoot(),
    FormsModule
  ],
  declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }

获取编辑组件中的数据或参数

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {

    this.route.snapshot.params['id'];
    this.route.snapshot.data['type'];

  }
}

【讨论】:

  • 你能在导航点而不是路由配置中将该数据传递到路由中吗?例如,在明细组件替换主组件(因此不是主组件的子组件)的主从情况下,您是否可以在导航到明细组件时将主数据对象传递给明细组件,以便明细组件可以显示一些它在加载详细数据时的数据?
  • @Sebastien 你得到你的答案了吗...请告诉你是怎么做到的
  • @Veerendra Borra — 我用data 对象设置了路由器配置,但在我的组件数据中仍然显示为空对象...有什么想法吗?
【解决方案3】:

你可以这样做:

app-routing-modules.ts:

import { NgModule                  }    from '@angular/core';
import { RouterModule, Routes      }    from '@angular/router';
import { PowerBoosterComponent     }    from './component/power-booster.component';


export const routes: Routes = [
  { path:  'pipeexamples',component: PowerBoosterComponent, 
data:{  name:'shubham' } },
    ];
    @NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}

在上述路径中,我想通过 pipeexamples 路径向 PowerBoosterComponent 发送数据。所以现在我可以像这样在 PowerBoosterComponent 中接收这些数据:

power-booster-component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';

@Component({
  selector: 'power-booster',
  template: `
    <h2>Power Booster</h2>`
})

export class PowerBoosterComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {
    //this.route.snapshot.data['name']
    console.log("Data via params: ",this.route.snapshot.data['name']);
  }
}

所以你可以通过this.route.snapshot.data['name']获取数据。

【讨论】:

  • 如果我想动态设置数据怎么办?例如,使用 router.navigate() 时?
  • 不要通过 cmets 提出新问题。先搜索,如果需要,再发布一个新问题。您可以像这样动态设置数据:- this.router.navigate(['/detail', this.object.id]);
  • 我注意到您只能在通过 DI 传递 ActivatedRoute 时获得它。为什么不能从Router 获取?
  • @ShubhamVerma:请您删除您的评论,因为它没有回答相当混乱的问题。您的示例将数据动态传递到 URL。问题是动态传递数据而不反映在 URL 中。
  • @S. Robijns:我认为在我的评论中,我正在回答如何在 router.navigate() 中传递数据,这并不令人困惑。请让我确定它是否令人困惑。
【解决方案4】:

1.设置路由以接受数据

{
    path: 'some-route',
    loadChildren: 
      () => import(
        './some-component/some-component.module'
      ).then(
        m => m.SomeComponentModule
      ),
    data: {
      key: 'value',
      ...
    },
}

2。导航到路线:

来自 HTML:

<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>

或来自 Typescript:

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

...

 this.router.navigate(
    [
       '/some-component',
       {
          key: 'value',
          ...
       }
    ]
 );

3.从路线获取数据

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

...

this.value = this.route.snapshot.params['key'];

【讨论】:

    猜你喜欢
    • 2017-02-28
    • 2016-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2016-08-18
    • 1970-01-01
    • 2014-03-24
    相关资源
    最近更新 更多