[英]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.