angular2使用Rounting发送参数到子组件

时间:2017-09-24 20:39:18

标签: angular parameters routing router

如果我执行“this.router.navigate([”./ resultadoBusqueda“],我试图在单击组件按钮时发送一个子组件(resultadoBusqueda.component)一系列参数, navigationExtras);”不起作用,而如果我使用routerlink“Child One”它确实工作并加载组件子,问题是使用routerlink我不能尝试一系列参数以后发送它们,我需要在使用路由器时这样做。导航。有什么想法吗?

Busqueda.component.html

<button (click)="EnviarQueryParams()">Enviar query params a resultadoBusquedaComponent.ts</button>
<!--<a [routerLink]="['./resultadoBusqueda']">Child One</a>-->
<router-outlet></router-outlet>

Busqueda.component.ts

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

@Component({
selector: 'app-busqueda-component',
templateUrl: './busqueda.component.html',
})

export class BusquedaComponent {
public constructor(private router: Router) { }

EnviarQueryParams(){
    let navigationExtras: NavigationExtras = {
        queryParams: {
            "firstname": "Nic",
            "lastname": "Raboy"
        }
    };
    this.router.navigate(["./resultadoBusqueda"], navigationExtras);
}
}

resultadoBusqueda.component.ts(子组件,此组件在“Busqueda.Component”的路由器插座中加载

import { Component, OnInit} from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject'
import {ActivatedRoute} from "@angular/router";   

@Component({
 selector: 'app-resultado-busqueda-component',
 templateUrl: './resultadoBusqueda.component.html',
 providers: [EmployeeService]
})

export class ResultadoBusquedaComponent  implements OnInit {  
public firstname: string;
public lastname: string;
constructor(private _employeeService: EmployeeService,private route: 
ActivatedRoute) {    }    

ngOnInit() {
this.route.queryParams.subscribe(params => {
  this.firstname = params["firstname"];
  this.lastname = params["lastname"];    
});
}
}

app.module.ts

// Some stuff ...
const appRoutes: Routes = [
{ path: 'busqueda', component: BusquedaComponent,
children: [{path: 'resultadoBusqueda',  component: 
ResultadoBusquedaComponent}]
},  
{ path: 'employees', component: EmployeeListComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];

// Some stuff ...
imports: [
 BrowserModule, FormsModule,  Ng2CompleterModule, HttpModule,  
 RouterModule.forRoot(appRoutes)    
 ],

1 个答案:

答案 0 :(得分:0)

您也可以使用RouterLink传递查询参数。它在Angular文档中讨论了here

您可以像这样添加查询参数:

<a routerLink="resultadoBusqueda" [queryParams]="navigationExtras">Child One</a>