2017-09-30 3 views
0

router.navigate ([ '/ some-route'])을 처리하는 더 나은 방법을 찾고 있습니다.각 4 : router.navigate()가 나머지 코드 실행을 멈추게하지는 않습니다

내 코드는 모두 을 console.log가 탐색이라고하지만 기록됩니다, 위의 코드에서

아래
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.'); 
    ... 
    } 
} 

같다.

가 나는 자바 스크립트의 동작에 따라 단순한 기능이 아닌 종료 문이며, 동작() router.navigate으로 일어나는 것을 알고있다.

예외는 브라우저 콘솔에없는 로그입니다.


위의 시나리오를 처리하는 데 더 나은 솔루션을 제공하는 사람이있어 탐색 후에도 코드의 나머지 부분이 실행되지 않도록 할 수 있습니까?

답변

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.'); 
    ... 
    } 
} 

이 너무 작동하지만 좋은 방법이 아닙니다해야한다.

+0

빠른 응답을 보내 주셔서 감사합니다. 내 문제는, 내 구성 요소에는 비동기 적으로 호출되는 무거운 논리적 구현이 있으며, 구성 요소 뷰가 종속되어 있고 논리에 따라 리디렉션이 발생하고 있다는 점입니다. ** AuthGuard **로 이동하면 구성 요소에서 동일한 구현을 다시 실행해야합니다. –

+0

논리 구현을 새로운 서비스로 옮겨서 AuthGuard에서 쉽게 사용할 수 있도록하는 것이 좋습니다. 간단한 해결 방법은 업데이트를 참조하십시오. –