source

Angular2 라우터(@angular/router), 기본 경로를 설정하는 방법은 무엇입니까?

factcode 2023. 8. 2. 09:27
반응형

Angular2 라우터(@angular/router), 기본 경로를 설정하는 방법은 무엇입니까?

@Routes 루트 메타데이터 컬렉션에서 기본 경로를 설정하려면 어떻게 해야 합니까?@angular/router-deprecommitted의 angular2 라우터를 사용하는 경우 경로 개체의 모음인 @routeConfig 개체에 경로를 정의하지만 이러한 경로 개체에는 더 많은 속성이 있습니다.예를 들어 'name' 및 'useAsDefault' 특성이 있는 반면 @angular/router에서 정의된 경로는 그렇지 않습니다.새 라우터를 사용하여 새 앱을 작성하고 싶은데, 새 라우터를 사용하고 기본 경로를 설정하려면 어떻게 해야 합니까?

이것은 나의 경로를 정의하는 나의 주요 앱 구성요소입니다.

import { Component } from '@angular/core';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ConfigManagerComponent } from './configManager/configManager.component';
import { ApplicationMgmtComponent } from './applicationMgmt/applicationMgmt.component';
import { MergeComponent } from './merge/merge.component';

import { ROUTER_DIRECTIVES, Routes } from '@angular/router';


@Component({
    selector: 'app-container',
    templateUrl: 'app/app.component.html',
    directives: [ROUTER_DIRECTIVES]
})

@Routes([

        { path: '/Dashboard', component: DashboardComponent },
        { path: '/ConfigManager', component: ConfigManagerComponent },
        { path: '/Merge', component: MergeComponent },
        { path: '/ApplicationManagement', component: ApplicationMgmtComponent }
])

export class AppComponent { }

다음과 같은 앵커 태그를 클릭하면 경로 정의가 제대로 작동하는 것 같습니다.

<li class="nav hidden-xs"><a [routerLink]="['./Dashboard']">Dashboard</a>/li>

연결된 경로로 전환됩니다.유일한 문제는 앱이 로드될 때 활성화된 경로가 없다는 것입니다.앱 부팅 시 활성화되는 기본 경로를 정의하려면 어떻게 해야 합니까?

감사합니다!

V2.0.0 이상

참고 항목: https://angular.io/guide/router#the-default-route-to-heroes

RouterConfig = [
  { path: '', redirectTo: '/heroes', pathMatch: 'full' },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '', redirectTo: '/detail', pathMatch: 'full' },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

모든 것을 잡을 수 있는 경로도 있습니다.

{ path: '**', redirectTo: '/heroes', pathMatch: 'full' },

URL을 "수정"하여 리디렉션합니다.

V3-알파(블라디보스토크)

경로 사용/그리고.redirectTo

RouterConfig = [
  { path: '/', redirectTo: 'heroes', terminal: true },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '/', redirectTo: 'detail', terminal: true },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

RC.1 @각형/라우터

RC 라우터가 아직 지원하지 않습니다.useAsDefault해결 방법으로 자세히 탐색할 수 있습니다.

루트 구성 요소

export class AppComponent {
  constructor(router:Router) {
    router.navigate(['/Merge']);
  }
}

다른 구성 요소의 경우

export class OtherComponent {
  constructor(private router:Router) {}

  routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree) : void {
    this.router.navigate(['SomeRoute'], curr);
  }
}

경로 경로를 '로 설정합니다.DashboardComponent의 예는 load first입니다.

@Routes([
        { path: '', component: DashboardComponent },
        { path: '/ConfigManager', component: ConfigManagerComponent },
        { path: '/Merge', component: MergeComponent },
        { path: '/ApplicationManagement', component: ApplicationMgmtComponent }
])

도움이 되길 바랍니다.

Angular 2+에서는 경로 모듈에 이 경로를 추가하여 기본 페이지로 경로를 설정할 수 있습니다.이 경우 로그인이 기본 페이지의 대상 경로입니다.

{path:'',redirectTo:'login', pathMatch: 'full' },

문서에 따르면 당신은 그냥.

{ path: '**', component: DefaultLayoutComponent }

app-message.sys.ts 소스: https://angular.io/guide/router

로드 시 RegistrationComponent를 로드하고 이벤트가 발생하면 ConfirmationComponent를 클릭한다고 가정합니다.

소인appModule.ts이렇게 쓰면 됩니다.

RouterModule.forRoot([
      { 
        path: '', 
        redirectTo: 'registration', 
        pathMatch: 'full'
       },
       { 
        path: 'registration', 
        component: RegistrationComponent
       },
      {
        path : 'confirmation',
        component: ConfirmationComponent
      }
    ]) 

OR

RouterModule.forRoot([
       { 
        path: '', 
        component: RegistrationComponent
       },
      {
        path : 'confirmation',
        component: ConfirmationComponent
      }
    ]) 

또한 괜찮습니다.마음에 드는 것을 고르세요.

경로를 기본 구성 요소로 만들려면 경로를 비워 두어야 합니다.

{ path: '', component: DashboardComponent },

저는 동일한 문제에 직면했습니다. 가능한 모든 해결책을 적용하지만 결국 이것이 제 문제를 해결합니다.

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}

이것이 당신에게 도움이 되기를 바랍니다.

방금 동일한 문제에 직면하여 컴퓨터에서 작동할 수 있도록 했습니다. 하지만 변경 사항은 설명서에 언급된 것과 동일한 방식이 아니므로 각도 버전 라우팅 모듈의 문제일 수 있습니다. 내 것은 각도 7입니다.

app-routes.ts에서 설정한 경로와 동일한 경로로 레이지 모듈 메인 경로 입력 경로를 변경했을 때만 작동했습니다.

routes = [{path:'', redirectTo: '\home\default', pathMatch: 'full'},
           {path: '', 
           children: [{
             path:'home',
             loadChildren :'lazy module path'      
           }]

         }];

 routes configured at HomeModule
 const routes = [{path: 'home', redirectTo: 'default', pathMatch: 'full'},
             {path: 'default', component: MyPageComponent},
            ]

 instead of 
 const routes = [{path: '', redirectTo: 'default', pathMatch: 'full'},
                   {path: 'default', component: MyPageComponent},
                ]

현재 버전의 angular 2에서는 경로에 '/'를 사용하거나 경로 이름을 지정할 수 없습니다."app.routes.ts"와 같은 경로 파일을 만들고 구성 요소를 가져오면 가져올 때 경로를 확인할 수 있습니다.

import { Component } from '@angular/core';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ConfigManagerComponent } from './configManager/configManager.component';
import { ApplicationMgmtComponent } from './applicationMgmt/applicationMgmt.component';
import { MergeComponent } from './merge/merge.component';`

추가:

import {RouterConfig, provideRouter } from '@angular/router';

다음 경로:

const routes:RouterConfig = [      
    { path: 'Dashboard', component: DashboardComponent },
    { path: 'ConfigManager', component: ConfigManagerComponent },
    { path: 'Merge', component: MergeComponent },
    { path: 'ApplicationManagement', component: ApplicationMgmtComponent }
 ];

그런 다음 내보내기:

export  const APP_ROUTER_PROVIDERS = [
    provideRouter(routes)]

Import에 .ts 파일이 .APP_ROUTER_PROVIDERS다음과 같이 라우터 공급자를 main.ts에 부트스트랩을 추가합니다.

bootstrap(AppComponent,[APP_ROUTER_PROVIDERS]);

마지막으로 링크는 다음과 같습니다.

li class="nav hidden-xs"><a [routerLink]="['./Dashboard']" routerLinkActive="active">Dashboard</a>/li>

경로에 다른 매개 변수를 추가하기만 하면 됩니다. 매개 변수는 useAsDefault:true입니다.예를 들어 Dashboard 구성 요소를 기본값으로 사용하려면 다음 작업을 수행해야 합니다.

@RouteConfig([
    { path: '/Dashboard', component: DashboardComponent , useAsDefault:true},
    .
    .
    .
    ])

경로에 이름을 추가하는 것이 좋습니다.

{ path: '/Dashboard',name:'Dashboard', component: DashboardComponent , useAsDefault:true}

언급URL : https://stackoverflow.com/questions/37605119/angular2-router-angular-router-how-to-set-default-route

반응형