라우팅에서 children 처리

라우팅에서 children 처리 updated_at: 2023-12-04 17:04

라우팅에서 children 처리

좀 더 복잡한 routes 생각해보자

심플한 라우터 예제

보통 url상에서 https://www.myservice.com/home 으로 하면 아래의 경로를 따라 HomePage를 호출하게 된다.

  • app-routing.module.ts
import { HomePage } from './home.page';
const routes: Routes = [
  { path: 'home', component: HomePage}
]

loadChildren 사용예제

위와 같은 경우는 심플한 서비스를 만들 경우이고 복잡한 경우는 초기 로딩 속도를 줄이기 위해 loadChildren 을 사용하게 된다.

  • app-routing.module.ts
import { HomePage } from './home.page';
const routes: Routes = [
  { path: 'home', component: HomePage},
  {
    path: 'auth',
    loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule)
  }
]

위 처럼 구성하게 되면 https://www.myservice.com/auth 를 호출하게 되면 ./auth/auth.module.ts 의 AuthModule 을 호출한다.
이 AuthModule 에서는 app-routing.module.ts 와 유사한 routes를 설정하게 되고 이 설정 값에 딸 하위 url로 들어가게 된다.
https://www.myservice.com/auth 호출시 AuthMainPage 을 호출하고
https://www.myservice.com/auth/friends 호출시 FriendsPage 를 호출하는 식으로...

  • auth-routing.ts

const routes: Routes = [
  { path: '', component: AuthMainPage},
  { path: 'friends', component: FriendsPage},
  .......
]

children 은 언제 사용하지?

angular는 모든 컨텐츠가 router-outlet 의 태그 안에 출력된다.
이해를 돕자면 router-outlet 은 iframe과 비슷하다.(물론 다르지만 그렇게 생각하자)
app.component.html 을 보면 router-outlet 이라는 태그가 존재하고 위에서 호출한 모든 url은 (/home, /auth, /auth/friend..)의 최종 콘텐츠는 이 router-outlet 안에 존재하게된다.
여기서 우리는 궁금증이 하나 생긴다. router-outlet은 app.component.html 에만 존재하여야 하는가?
html에서도 iframe 속에 iframe을 넣어 공동된 디자인은 밖으로 빼고 안의 콘텐츠 내용만 iframe url을 변경하며 바꾸지 않았던가?
바로 그때 사용가능한 것이 children 이다.

  • app-routing.module.ts
import { HomePage } from './home.page';
const routes: Routes = [
  { path: 'home', component: HomePage},
  {
    path: 'auth',
    loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule)
  },
  {
    path: 'child',
    loadChildren: () => import('./child/child.module').then(m => m.ChildModule)
  }
]
  • child-routing.module.ts
const routes: Routes = [
  {
    path: '',
    redirectTo: 'child/tab1',
    pathMatch: 'full'
  },

  {
    path: 'child',
    component: ChildComponent,
    children: [
      {
        path: 'tab1',
        component: Tab1Component
      },
      {
        path: 'tab2',
        component: Tab2Component
      },
    ]
  },
];

여기서 https://www.myservice.com/child/tab1 을 호출한다고 생각하자.
이럴경우 위의 route를 따라 가면 먼저 child라는 ChildComponent 를 읽어 들이고 이 ChildComponent 에 정의된 router-outlet 에 tab1의 Tab1Component 의 결과 물이 출력된다.

ChildComponent.ts

@Component({
template: `<router-outlet></router-outlet>`,
})
export class ChildComponent implements OnInit {

}

결과적으로는 app.component.html에 지정된 router-outlet 에 ChildComponent의 결과 물이 출력되고 ChildComponent에 정의 된 router-outlet 에 Tab1Component 의 결과물이 출력되는 형식이 된다.

평점을 남겨주세요
평점 : 5.0
총 투표수 : 2

질문 및 답글