如何通过路由传递动态数据?

时间:2016-09-14 14:10:58

标签: angular angular2-routing

我想通过路由将search-products.component.ts中的过滤器权限发送到ProductsListComponent。可能吗?

我能够传递静态数据,但动态数据呢?

这是我的演示代码:

app.routing.ts

import { Routes, RouterModule } from '@angular/router';

import { SearchProductsComponent } from './search-products/search-products.component';
import { ProductsListComponent } from './products-list/products-list.component';

const routes: Routes = [
    { path: 'search-products', component: SearchProductsComponent },
    { path: 'products-list', component: ProductsListComponent,data:{key:'value'}}
];

export class AppRoutingModule { }

export const AppRoutingRoutes = RouterModule.forRoot(routes);

搜索-products.component.ts

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

@Component({
    selector: 'search-products',
    templateUrl: 'search-products.component.html',
})

export class SearchProductsComponent implements OnInit {

    filters = { warehouses: ['A','B'], locations: ['Europe','America']}; 

    constructor(private router : Router) { }

    ngOnInit() {}

    goToProductsList() {
        this.router.navigate(['/products-list']);
    }


}

1 个答案:

答案 0 :(得分:1)

你可以尝试

this.router.navigate(['/products-list',encodeURI(JSON.stringify(this.filters))]);

将路线更改为:

const routes: Routes = [
  { path: 'search-products', component: SearchProductsComponent },
  { path: 'products-list/:data', component: ProductsListComponent}
];
product-list

中的

和JSON.parse(decodeURI(data))