【问题标题】:angular2 send parameter using Rounting to child componentangular2使用Routing将参数发送到子组件
【发布时间】:2017-09-24 20:39:18
【问题描述】:

我试图在单击组件按钮时向子组件 (resultadoBusqueda.component) 发送一系列参数,如果我执行“this.router.navigate(["./resultadoBusqueda"],导航附加);"不起作用,而如果我使用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”的router-outlet中

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)    
 ],

【问题讨论】:

    标签: angular parameters routing router


    【解决方案1】:

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

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

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

    【讨论】:

    • 我不能这样做,因为当我点击按钮时变量“resultadoBusqueda”被填充。它是根据我在单击按钮时而不是之前必须检查的一些条件填充的。
    猜你喜欢
    • 2018-12-27
    • 2017-01-06
    • 2016-07-24
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 2017-10-23
    相关资源
    最近更新 更多