【问题标题】:Angular 4: router.navigate() does not ensure to stop execution rest of the codesAngular 4:router.navigate() 不能确保停止执行其余代码
【发布时间】:2017-09-30 10:05:39
【问题描述】:

我正在寻找一种更好的方法来处理 router.navigate(['/some-route'])

我的代码如下所示

class SomeComponent implements OnInit, AfterViewInit {
  ngOnInit() {
    ...
    router.navigate(['/some-route']);
    ...
    console.log('This line will be logged.');
  }

  ngAfterViewInit() {
    ...
    console.log('This line will also be logged.');
    ...
  }
}

在上面的代码中,虽然调用了导航,但 console.log 都会被记录。

我知道这是因为 router.navigate() 只是一个函数而不是终止语句,并且根据 JavaScript 行为运行。

我的例外是,所有日志都不应该在浏览器控制台中。


谁能帮助我提供更好的解决方案来处理上述情况,以便我可以确保导航后不会执行其余代码?

【问题讨论】:

    标签: javascript angular angular2-routing angular-router


    【解决方案1】:

    ngAfterViewInit 将始终被执行,您可能想使用 CanActivate 守卫,所以尝试这样的事情:

    import { Injectable } from '@angular/core';
    import { CanActivate, Router } from '@angular/router';
    import { AuthService } from './auth.service';
    
    @Injectable()
    export class SomeComponentGaurd  implements CanActivate {
    
      constructor(private router :Router) {}
    
      canActivate() {
         if( /** some condition*/){
              this.router.navigate(['/some-route']);
            // will access to the component
            return false;
         }else{
             // won't access to the component
             return true;
         }
      }
    }
    

    路由配置:

    export const AppRoutes:RouterConfig = [
      { 
        path: 'some-cmp',
        component: SomeComponent,
        canActivate: [SomeComponentGaurd]
      }
    ];
    

    这将阻止ngOnInit 被执行。

    不使用 AuthGuard 的简单解决方法:

    class SomeComponent implements OnInit, AfterViewInit {
      private getOut : boolean = false;
      ngOnInit() {
        ...
        if(/** some condition*/){
           this.getOut = true;
           return router.navigate(['/some-route']); // don't forget to return
        }
    
        ...
        console.log('This line will  be logged.');
      }
    
      ngAfterViewInit() {
        ...
        if(this.getOut){
           return;
        }
        console.log('This line will also be logged.');
        ...
      }
    }
    

    这也应该有效,但不是一个好习惯。

    【讨论】:

    • 感谢您的快速回复。我的问题是,在我的组件中,有一些异步调用的重逻辑实现,其中组件视图依赖于,并且重定向也基于逻辑发生。如果我将它们移动到 AuthGuard 这里,我需要再次在组件中运行相同的实现。
    • 将这些逻辑实现移动到新服务是一个很好的做法,这样您就可以在 AuthGuard 中轻松使用它,请参阅更新以获得简单的解决方法。
    猜你喜欢
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 2012-11-09
    • 1970-01-01
    相关资源
    最近更新 更多