[英]Prevent Angular component rendering after router.navigate
如果在 ngOnInit 中执行 this.router.navigate([' ngOnInit
this.router.navigate(['someRoute'])
,初始组件仍然在重定向之前被渲染。
例如我有一些组件:
@Component({
selector: 'my-app',
template: '<child-comp></child-comp>',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(private router: Router) {
}
ngOnInit() {
console.log('ngOnInit from AppComponent');
this.router.navigate(['another']);
}
}
它在模板中包含子项:
@Component({
selector: 'child-comp',
template: '<div>CHILD<div>'
})
export class ChildComponent {
ngOnInit() {
console.log('Should NOT be called (ChildComponent)');
}
}
在视图初始化之前(在ngOnInit
钩子内),我执行重定向到另一个组件:
@Component({
selector: 'another-comp',
template: '<div>Another<div>'
})
export class AnotherComponent {
ngOnInit() {
console.log('Should be called (AppComponent)');
}
}
我希望子组件不会被初始化,因为它发生在重定向调用之后,但它的ngOnInit()
钩子仍然被触发。
在这种情况下如何防止子组件初始化?
Stackblitz: https://stackblitz.com/edit/angular-gjunnr?file=src%2Fapp%2Fanother%2Fanother.component.ts
PS我没有找到阻止组件渲染并最终修改设计的方法。
这就是警卫的用途:
创建一个守卫,确定是否允许用户 go 到该页面:
@Injectable({
providedIn: 'root'
})
export class PreventNavigateGuard implements CanActivate {
constructor(public router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
return this.router.createUrlTree(["another"]);
}
}
然后在您的路线中使用 canActivate 来保护它:
const appRoutes: Routes = [
{ path: '', component: AppComponent, canActivate: [PreventNavigateGuard] },
{ path: 'another', component: AnotherComponent },
];
https://angular.io/guide/router#milestone-5-route-guards
这是一个堆栈闪电战: https://stackblitz.com/edit/angular-kbzx1v
或者,您可以只将ngIf
应用于子组件,并且仅在app.component
中的属性为 true 时才呈现它。
<child-comp *ngIf="false"></child-comp>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.