programing

Angular 2에서 라우팅을 추적하는 방법은 무엇입니까?

iphone6s 2023. 8. 15. 10:55
반응형

Angular 2에서 라우팅을 추적하는 방법은 무엇입니까?

라우팅 설정 파일이 분리된 구성 요소가 있습니다.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { Route } from '../core/route.service';
import { extract } from '../core/i18n.service';
import {CalendarThematicPlanComponent} from './calendar-thematic-plan.component';

const routes: Routes = Route.withShell([
  { path: 'calendar', component: CalendarThematicPlanComponent }
]);

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: []
})

export class CalendarThematicPlanRoutingModule { }

URL 주소를 입력하는 경우:http://localhost:4200/calendar홈 페이지로 리디렉션됩니다.

Angular 2에서 라우팅을 추적하려면 어떻게 해야 합니까?

다음 옵션을 사용하여 두 번째 인수를 전달할 수 있습니다.

imports: [
    RouterModule.forRoot(
      routes,
      { enableTracing: true } // <-- debugging purposes only
    )
]

그런 다음 Angular는 모든 이벤트를 문서에 따라 브라우저 콘솔에 기록합니다.

추적을 활성화하시겠습니까?부울의
true이면 모든 내부 탐색 이벤트를 콘솔에 기록합니다.디버깅에 사용합니다.

가장 많이 받아들여진 답변의 댓글들이 암시하듯이, 이것은enableTracing에서 작동하지 않습니다.forChild방법.간단한 해결 방법은 에서 모든 라우팅 이벤트를 구독하는 것입니다.AppModule이와 같이:

export class AppModule {

  constructor(
    private readonly router: Router,
  ) {
    router.events
      .subscribe(console.log)
  }

}

devqons에 대한 훌륭한 답변 외에도: 와일드카드 경로에 대해 일시적으로 의견을 제시하면 경로 정의를 디버깅하는 것이 훨씬 쉬워집니다.와일드카드 경로는 생산 과정에서 유용합니다. 예를 들어,NotFound구성 요소이지만 디버깅하는 동안 문제가 발생합니다.

예:

const routes: Routes = [
    ... (your route definions)

    // If you have a catch-all route defined, outcomment is like below
    // {
    //     path: '**',
    //     redirectTo: '/error/not-found',
    // },
];

catch-all 경로를 설명하지 않으면 라우터는 사용자의 오류를 무시하지 않고 사용자의 정의와 일치하지 않는 경로를 브라우저 콘솔에 정확하게 표시합니다.

예를 들어, 다음 오류가 표시되는 경우:

core.js:4002 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'projects/123'
Error: Cannot match any routes. URL Segment: 'projects/123'
    at ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:2459)

경로 정의에서 '129/123'을(를) 일치시키는 데 문제가 있다는 것을 즉시 알았습니다.

비록 제가 이것에 답하기에는 늦었지만요.하지만 Angular의 초보자들에게는 유용할 수도 있습니다.

각도 경로 변경을 추적할 수 있는 두 가지 방법이 있습니다.

라우터 모듈(추적 활성화)

설정할 수 있습니다.enableTracing로.RouterModule그러면 모든 경로 변경 이벤트가 기록됩니다.

RouterModule.forRoot(routes, { 
  enableTracing: true,    /* <-- Set this to true */
}),

구독Router.events

모든 라우터 변경 이벤트를 추적하지 않으려면 다음을 구독할 수 있습니다.Router.events특정 경로 변경 이벤트를 필터링할 수 있습니다.

constructor(
  private router: Router,
  /* Other dependencies */
) {

  this.router.events
    .pipe(
      // You can also use traditional if else in the subscribe 
      filter(event => event instanceof NavigationStart)
    )
    .subscribe(event => {
      console.group(`Router event: ${event.constructor.name}`);
      console.log(event);
      console.groupEnd();
    });
}

독립 실행형 구성 요소로 작업하고 라우팅을 부트스트랩하는 경우main.ts파일, 이 구성을 함수에 대한 호출로 전달합니다.withDebugTracing:

// main.ts

bootstrapApplication(AppComponent, {
  providers: [
    provideRouter(
      MY_APP_ROUTES, // first argument is your routes array
--->  withDebugTracing(), // second argument and beyond are router features to be enabled
    ),
  ],
}).catch(console.error);

출처: https://angular.io/guide/standalone-components#configuring-dependency-injection

언급URL : https://stackoverflow.com/questions/45669030/how-to-trace-routing-in-angular-2

반응형