《Angular2入门系列实践》——如何实现路由传值

背景

     Angular项目下一个路由如何接收到上一个路由url中的参数id?

解决方案

    1.父路由routes配置方式:

<span style="color:#000000"><code>export const  <span style="color:#009900">EvaluationQuestionnaireRoute</span>=[
    {
    <span style="color:#009900">path:</span><span style="color:#009900">':edit/:id'</span>, <span style="color:#008800">//</span>必须是路径名<span style="color:#009900">:/id</span>
    <span style="color:#009900">component:</span><span style="color:#009900">EditQuestionnaireComponent</span>
    },</code></span>
  • 1
  • 2
  • 3
  • 4
  • 5

    2.跳转传参方式:

<span style="color:#000000"><code>模板:
<span style="color:#006666"><<span style="color:#4f4f4f">div</span> [<span style="color:#4f4f4f">routerLink</span>]=<span style="color:#009900">"['edit',1]"</span>></span>页面跳转传值<span style="color:#006666"></<span style="color:#4f4f4f">div</span>></span>
</code></span>
  • 1
  • 2
  • 3
<span style="color:#000000"><code>控制器:
import { Router } <span style="color:#000088">from</span> <span style="color:#009900">'@angular/router'</span>;
<span style="color:#000088">this</span>.router.navigateByUrl(<span style="color:#009900">"edit/"</span>+q.id);
<span style="color:#000088">this</span>.router.navigate([<span style="color:#009900">"edit/"</span>,q.id]);</code></span>
  • 1
  • 2
  • 3
  • 4

    3.子路由获取父路由参数:

<span style="color:#000000"><code>

import { Component, OnInit } from <span style="color:#009900">'@angular/core'</span>;
import {ActivatedRoute} from <span style="color:#009900">"@angular/router"</span>;

@Component({
  selector: <span style="color:#009900">'app-product'</span>,
  templateUrl: <span style="color:#009900">'./product.component.html'</span>,
  styleUrls: [<span style="color:#009900">'./product.component.scss'</span>]
})
export <span style="color:#000088">class</span> <span style="color:#4f4f4f">ProductComponent</span> <span style="color:#000088">implements</span> <span style="color:#4f4f4f">OnInit</span> {

constructor(<span style="color:#000088">public</span> route: ActivatedRoute) {}

  ngOnInit() {
        <span style="color:#880000">//通过订阅这种形式来接收父级页面传过来的值                              this.activatedRoute.params.subscribe(</span>
      data=>{
      <span style="color:#000088">this</span>.id=data.id;
      console.log(data.id)}
    );
        <span style="color:#880000">//或者通过</span>
    <span style="color:#000088">this</span>.route.params[<span style="color:#009900">'value'</span>][<span style="color:#009900">'id'</span>]
        <span style="color:#880000">//或者通过</span>
    <span style="color:#000088">this</span>.id = <span style="color:#000088">this</span>.activatedRoute.snapshot.params[<span style="color:#009900">'id'</span>];
  }

}

</code></span>
结语

   本篇主要目的是解决路由传值的问题,想更多了解关于路由问题,请看我的更多文章!

猜你喜欢

转载自blog.csdn.net/xwnxwn/article/details/81631272