2017-10-30 15 views
1

이것이 좋은 연습인지 아닌지는 잘 모르겠습니다. 나는이 개 게으른로드 된 모듈 데canLoad 가드와 함께 ngrx-store를 만드는 방법

: ManagementModuleConfigurationModule을하고, 경로 설정은 다음과 같습니다 : 기본적으로

const routes: Routes = [ 
    {path: '', redirectTo: 'management', pathMatch: 'full'}, { 
    path: 'configuration', 
    loadChildren: './configuration/configuration.module#ConfigurationModule', 
    canLoad: [UnconfiguredGuard] 
    }, 
    { 
    path: 'management', 
    loadChildren: './management/management.module#ManagementModule', 
    canLoad: [ConfiguredGuard] 
    } 
] 

아이디어가 시스템 상태를 확인했고 그러나 아래에 내가 뭘하려고 오전입니다 다른 단계로 리디렉션합니다 (예 : sys가 아직 구성되지 않은 경우 /configuration으로 리디렉션하십시오. 그렇지 않으면 /management으로 리디렉션하십시오.

// ConfiguredGuard: 
canLoad(route) { 
    return this.configService.isConfigured() 
     .do((configured: boolean) => { 
      if (!configured) { 
      // redirect to /configuration if unconfigured 
      this.router.navigate(['/configuration']); 
      } 
     }) 
} 

지금 나는 모든 @ ngrx/{저장, 효과, 라우터 매장} libs와 채택하기 원하고, 위 가드 : 나는이 프로젝트에 @ngrx/store를 추가하기 전에

, 두 canLoad 가드은 간단합니다 다음으로 변경된다 : 물론

canLoad(route) { 
    this.store.dispatch(new CheckInitStatus()); 
    return this.store.select('initStatus') 
     .filter(s => s.checked) // check only when loaded 
     .map(s => s.status === 'initialized') 
     .catch(() => of(false)); 
} 

, 부작용이 정의된다

@Effect() 
    check$: Observable<InitStatusAction> = this.actions$ 
    .ofType<CheckInitStatus>(CHECK_INITSTATUS) 
    .mergeMap(() => this.fetchInitStatus()) 
    .map(status => new InitStatusChecked({status, checked: true})) 
    .catch(e => of(new InitStatusCheckFailure(e))); 

그러나 내비게이션이 발생하지 않았으므로 ROUTER_NAVIGATION 액션이 발생하지 않습니다. 내가 여기에 놓친 게 있니? 그리고 이것이 훌륭한 연습인지 아닌지 궁금합니다. 내가 canActivate 가드 사용의 몇 가지 예를 찾았지만 canLoad 가드의 경우는 없습니다. 도와주세요, 고마워요!

답변

1

디버깅 하루 종일 마침내 알아 냈습니다! 수정은 매우 간단합니다. 또는 take(1)filter() 이후의 운영자 체인에 추가하면 지금 느낌을 표현할 수 없지만 RxJS를 올바르게 사용하기 위해서는 사고 방식이 필요하다는 것을 알고 있습니다.

canLoad(route) { 
    this.store.dispatch(new CheckInitStatus()); 
    return this.store.select('initStatus') 
     .filter(s => s.checked) // check only when loaded 
     .first() // or equivalently take(1) 
     .map(s => s.status === 'initialized') 
     .catch(() => of(false)); 
} 

좀 더 신중하게 canActivate의 예를 읽어야이 take(1)/first() 연산자는 예를 들어, 모든이 : https://toddmotto.com/preloading-ngrx-store-route-guards

+0

안녕하세요 @RoyLing! 이 답변을 주셔서 감사합니다, 그것은 많은 도움이되었습니다 (나는 같은 문제를 안고있었습니다). 경로 탐색을 어디에서 호출했는지 말해 줄 수 있습니까? 구성 요소 내부에서 ngrx 효과를 호출합니까? w –

+0

@ PedroArantes 이것은 오래 전의 프로젝트에서 문제였습니다. 당시 내가하고있는 것을 거의 잊어 버렸습니다 ... 어쨌든, 저는 이 가드 자체의 네비게이션은 각도 doc의 예제를 따라하면됩니다. 희망이 도움이됩니다. –