首页 > 解决方案 > Angular 6 - 导航到子路由刷新整个页面

问题描述

所以我正在使用 Angular 6,我试图从父路由导航到子路由。导航成功,但是在呈现子组件时会出现不需要的页面刷新。换句话说,导航可以正常工作,但它也会无缘无故地刷新页面。这是我的代码:

const appRoutes: Routes = [
    {
        path: "parent/:param1/:param2", component: ParentComponent,
        children: [
            { path: ":param3", component: ChildComponent }
        ]
    },
    { path: "", redirectTo: "/index", pathMatch: "full" },
    { path: "**", redirectTo: "/index" }
];

我的父组件如下所示:

import { Component } from "@angular/core";
import { ActivatedRoute } from "@angular/router";

@Component({
    selector: "my-parent",
    templateUrl: "./parent.component.html"
})

export class ParentComponent {
    param1: string;
    param2: string;
    loading: boolean;
    tutorials: any[];

constructor(public route: ActivatedRoute) {
    this.loading = true;
    this.param1= this.route.snapshot.params.param1;
    this.param2 = this.route.snapshot.params.param2;
    // get data here
    }
}

我的子组件如下所示:

import { Component } from "@angular/core";
import { ActivatedRoute } from "@angular/router";

@Component({
    selector: "my-child",
    templateUrl: "./child.component.html"
})
export class ChildComponent {
    param1: string;
    param2: string;
    param3: string;
    loading: boolean;
    result: any;

    constructor(public route: ActivatedRoute) {
        this.loading = true;
        this.param1= this.route.snapshot.params.param1;
        this.param2 = this.route.snapshot.params.param2;
        this.param3 = this.route.snapshot.params.param3;

   }
}

现在,我尝试从父组件导航到子组件的方式如下:

<a [routerLink]="['/parent', param1, param2, param3]">             
    <b>Navigate</b>
</a>

正如我所说,导航是成功的,但是有一个不需要的页面刷新,我想摆脱它并且我无法找到一个有效的解决方案。我真的不知道是什么原因造成的。我是 Angular 6 的新手。

提前感谢您的回答。

编辑:添加父组件 html

<router-outlet></router-outlet>
<div class="row" *ngIf="route.children.length === 0">
    // content here
</div>

标签: javascriptangulartypescript

解决方案


所以我找到了一个可行的解决方案,虽然不是很优雅,但它......有效。在我的父组件中,我创建了一个像这样的方法:

constructor(public route: ActivatedRoute, private router: Router) {
    this.loading = true;
    this.param1 = this.route.snapshot.params.param1;
    this.param2 = this.route.snapshot.params.param2;
    // get data
}

navigateToChild(param3: string) {
    this.router.navigate([param3], { relativeTo: this.route });
}

在父模板中,我这样做了:

<a (click)="navigateToChild(paramFromServer)">
    <b>Navigate</b>
</a>

这个没有更多的刷新。

谢谢大家的帮助。


推荐阅读