Angular 4获取儿童路线参数

时间:2018-02-20 16:11:24

标签: angular angular-routing

在我的申请中,路线是这样的: -

import os
import xml.etree.ElementTree as ET
filename = 'excercise.xml'
cwd = os.getcwd()
fullFile = os.path.abspath(os.path.join(cwd,filename))
tree = ET.parse(fullFile)
root = tree.getroot()

#Below code will get Child tag and Child attributes
for child in root:
    if (child.tag) == "source" and (child.attrib['mount'] == "/main.mp3") :
        for element in child:
            if element.tag == "source_ip":
                print(element.text)

现在在{ path: 'route-a', component: ComponentA, children : [ { path: ':param-b', component: ChildComponentB, children : [ { path: ':param-c', component: ChildComponentC } ]} ]}, 我正在尝试订阅子参数以获取ComponentA

param-b

现在,当我导航到 this.routefirstChild$ = this.route.firstChild.params.subscribe($routefirstChild => { console.log($routefirstChild, '$routefirstChild'); }); 时,我收到example.com/route-a错误。

但如果我导航到this.route.firstChild is null,那么param就会通过。必须订阅的哪个observable不会触发错误,但会在激活路径时传递子参数。

2 个答案:

答案 0 :(得分:1)

角度9

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<div class="row">
    <div class="col-12">
        <div class="card shadow mb-5">
            <h5 class="card-header">Bar Chart</h5>
            <div class="card-body">
                <div id="container">
                    <svg></svg>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>	
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.15.1/d3.min.js"></script>

ActivatedRoute仅保存当前路由(部分)。这意味着,如果您位于/ xyz,则如果有参数,您的ActivatedRoute将保存/ xyz /:id。如果您当前在父路径中,并且想访问子路径中的参数,则可以按上述方式调用;或者,如果您想使用大子路径参数,则可以使用this.activatedRoute.firstChild.paramMap.pipe(tap()).subscribe(params => { const id = params.get('id'); }); 在此处做出反应,然后订阅paramMap,如上所示。同样,您也可以使用ActivateRoute.parent而不是firstChild进入路由层次结构。

希望这会有所帮助!

答案 1 :(得分:0)

我最终实施了以下解决方案: -

import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';

     this.routeEvents$ = this.router.events.subscribe(

     ( $routeEvents ) : void => {

        if ( $routeEvents instanceof NavigationEnd ) {

            if(typeof this.route.firstChild != "undefined" && this.route.firstChild){

                console.log(this.route.firstChild.snapshot.params, 'this.route.firstChild.snapshot.params');

            }

        }

     });