Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 阻止router.navigate之后的角度组件渲染_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 阻止router.navigate之后的角度组件渲染

Javascript 阻止router.navigate之后的角度组件渲染,javascript,angular,typescript,Javascript,Angular,Typescript,如果要执行this.router.navigate(['someRoute'])内部ngOnInit,则在重定向之前仍会呈现初始组件 例如,我有一些组件: @Component({ selector: 'my-app', template: '<child-comp></child-comp>', styleUrls: [ './app.component.css' ] }) export class AppComponent { constructor

如果要执行
this.router.navigate(['someRoute'])
内部
ngOnInit
,则在重定向之前仍会呈现初始组件

例如,我有一些组件:

@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: 'another-comp',
  template: '<div>Another<div>'
})
export class AnotherComponent  {
  ngOnInit() {
    console.log('Should be called (AppComponent)');
  }
}
我希望子组件不会被初始化,就像重定向调用之后发生的那样,但它的
ngOnInit()
hook仍然会被触发

在这种情况下,如何防止子组件初始化

Stackblitz:


p.S.我没有找到阻止组件渲染并最终修改设计的方法。

这就是防护的作用:

创建用于确定是否允许用户进入该页面的防护:

@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"]);
  }
}


这里有一个stackblitz:

或者,您可以对子组件应用一个
ngIf
,并且仅当
app.component
中的属性为true时才渲染它

<child-comp *ngIf="false"></child-comp>


但在这种情况下,用户应转到“其他”组件页面。没关系。问题是,在这之后,旧组件不应该被渲染。我们为路由而不是模板中的子组件提供保护。如果是这样,我认为@Flignats建议将是我的下一次尝试。
const appRoutes: Routes = [
  { path: '', component: AppComponent, canActivate: [PreventNavigateGuard] },
  { path: 'another', component: AnotherComponent },
];
<child-comp *ngIf="false"></child-comp>