【问题标题】:@Input with router.navigate angular4@Input 与 router.navigate angular4
【发布时间】:2017-07-26 19:50:22
【问题描述】:

如何在 Angular 4 环境中通过 router.navigate 将值传递给 @Input? 内联工作正常:

<app-clinicdetail [clinicCode]="detailclinic"></app-clinicdetail>

但我想要的是

this.router.navigate(['/clinicdetail'])

传值。

【问题讨论】:

  • 通过路由传递给@Input。如果你想在路由时传递数据,它通过路由器参数。
  • 查看此文档,了解如何通过组件导航发送额外属性。angular.io/api/router/NavigationExtras
  • 这仍然会在 URL 中公开您的数据,如果这符合您的需要没关系,否则您必须使用自定义服务来存储和检索数据。

标签: angular url-routing


【解决方案1】:

这是一种使用 navigate 将参数传递给路由加载的组件的方法。

Angular 4 创建 URL 和路由的方式是这样的:

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(private router: Router) { }

  ngOnInit() {
  }

  onLoadServers(id: number){
    this.router.navigate(['/servers', id, 'edit'],{queryParams: {allowEdit: '1'}, fragment: 'loading'});
  }

} 

由于 onLoadServers() 中的 navigate 命令,您将收到以下路线视图:

http://localhost:4200/servers/1/edit?allowEdit=1#loading

在通过此路由加载的组件中,您可以通过以下方式接收查询参数和片段(正在加载 - 在这种情况下):

constructor(private route: ActivatedRoute) { }

ngOnInit() {
  console.log(this.route.snapshot.queryParams);//{allowEdit:"1"}
  console.log(this.route.snapshot.fragment);//loading
}

【讨论】:

    猜你喜欢
    • 2018-08-29
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2011-08-28
    • 2016-11-03
    • 1970-01-01
    相关资源
    最近更新 更多