【发布时间】:2018-08-07 10:35:40
【问题描述】:
所以我正在使用 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>
【问题讨论】:
-
你在哪个模块声明了childComponent?
-
我只有一个模块,ParentComponent 和 ChildComponent 都在主应用模块中声明
-
这不是最佳做法。所有子组件都应在其父模块中声明。他们的路由应该在父级的 routingModule 中指定。而在 app-routing.module 中,只有 parentModule 必须使用 loadChildren 属性指定。这就是延迟加载以有效方式工作的方式,从而提高渲染速度并且不会出现页面刷新问题。
-
我会调查的。对此相当陌生,因此欢迎任何和所有最佳实践提示。
-
这样会更好
标签: javascript angular typescript