programing

Angular 2 옵션루트 파라미터

javaba 2022. 11. 5. 11:08
반응형

Angular 2 옵션루트 파라미터

Angular 2 루트에 옵션 루트 파라미터를 설정할 수 있습니까?RouteConfig에서 Angular 1.x 구문을 시도했지만 다음 오류가 발생했습니다.

"ORiginal Exception: 경로 "/user/:id?"에 루트 구성에서 허용되지 않는 "?"가 포함되어 있습니다.

@RouteConfig([
{
    path: '/user/:id?',
    component: User,
    as: 'User'
}])

파라미터와 파라미터 없이 여러 루트를 정의할 수 있습니다.

@RouteConfig([
    { path: '/user/:id', component: User, name: 'User' },
    { path: '/user', component: User, name: 'Usernew' }
])

컴포넌트의 옵션 파라미터를 처리합니다.

constructor(params: RouteParams) {
    var paramId = params.get("id");

    if (paramId) {
        ...
    }
}

관련 github 문제도 참조해 주세요.https://github.com/angular/angular/issues/3525

{path: 'users', redirectTo: 'users/', pathMatch: 'full'},
{path: 'users/:userId', component: UserComponent}

이렇게 하면 매개 변수가 추가될 때 구성 요소가 다시 렌더링되지 않습니다.

정보가 선택 사항인 경우 쿼리 매개 변수를 사용하는 것이 좋습니다.

루트 파라미터 또는 쿼리 파라미터

확실한 규칙은 없다.일반적으로는

route 파라미터가 우선되는 경우

  • 값은 필수입니다.
  • 이 값은 루트 경로를 다른 경로와 구별하기 위해 필요합니다.

쿼리 파라미터를 선호한다.

  • 값은 옵션입니다.
  • 값은 복잡하거나 다변수입니다.

https://angular.io/guide/router#optional-route-parameters 에서

루트 경로에서 파라미터를 삭제하기만 하면 됩니다.

@RouteConfig([
{
    path: '/user/',
    component: User,
    as: 'User'
}])

Angular 4 - 옵션 파라미터의 순서를 해결하는 솔루션:

다음 작업을 수행합니다.

const appRoutes: Routes = [
  {path: '', component: HomeComponent},
  {path: 'products', component: ProductsComponent},
  {path: 'products/:id', component: ProductsComponent}
]

에 주의:products ★★★★★★★★★★★★★★★★★」products/:id루트의 이름은 완전히 동일합니다.는 4로 하다를 .products가 있는 경우 는 " "에 이어"로 이동합니다.products/:id.

루트 입니다.products에는 후행 슬래시를 사용할 수 없습니다.그렇지 않으면 angular가 파라미터 경로로 잘못 처리하지 않습니다.그래서 제 경우에는 제품에 대한 후행 슬래시가 있었는데 작동하지 않았습니다.

이 조작은 하지 마세요.

...
{path: 'products/', component: ProductsComponent},
{path: 'products/:id', component: ProductsComponent},
...

Rezz의 답변은 꽤 괜찮지만 한 가지 심각한 결함이 있습니다.이 원인이 되다User the component to run to component 。ngOnInit★★★★★★ 。

여기서 무거운 작업을 수행하고 비파라미터 경로에서 파라메트릭 경로로 전환할 때 다시 실행되지 않도록 하는 경우 문제가 발생할 수 있습니다.이들 2개의 루트는 옵션의 url 파라미터를 모방하는 것으로, 2개의 다른 루트가 되지 않습니다.

이 문제를 해결하기 위해 제안하는 것은 다음과 같습니다.

const routes = [
  {
    path: '/user',
    component: User,
    children: [
      { path: ':id', component: UserWithParam, name: 'Usernew' }
    ]
  }
];

매개 하는 논리를 '하다'로 할 수 .UserWithParam컴포넌트 및 기본 로직은 에 남습니다.User요소.에서 무엇을 하든User::ngOnInit/user에서 /user/123으로 이동하면 다시 실행되지 않습니다.

잊지 말고 꼭 넣어주세요.<router-outlet></router-outlet>에서User의 템플릿

여기서 제시된 답변(복수의 루트엔트리를 추가하는 것을 제안하는 rerezz에서 받아들여진 답변 포함)은 정상적으로 동작합니다.

단, 컴포넌트는 루트엔트리 간에 변경 시(파라미터가 있는 루트엔트리와 파라미터가 없는 엔트리 간에 변경 시) 재생성됩니다.

이를 회피하려면 양쪽 루트에 일치하는 독자적인 루트매처를 작성할 수 있습니다.

export function userPageMatcher(segments: UrlSegment[]): UrlMatchResult {
    if (segments.length > 0 && segments[0].path === 'user') {
        if (segments.length === 1) {
            return {
                consumed: segments,
                posParams: {},
            };
        }
        if (segments.length === 2) {
            return {
                consumed: segments,
                posParams: { id: segments[1] },
            };
        }
        return <UrlMatchResult>(null as any);
    }
    return <UrlMatchResult>(null as any);
 }

다음으로 루트 설정에서 매처를 사용합니다.

const routes: Routes = [
    {
        matcher: userPageMatcher,
        component: User,
    }
];

angular4에서는 계층별로 루트를 정리하기만 하면 됩니다.

const appRoutes: Routes = [
  { 
    path: '', 
    component: MainPageComponent 
  },
  { 
    path: 'car/details', 
    component: CarDetailsComponent 
  },
  { 
    path: 'car/details/platforms-products', 
    component: CarProductsComponent 
  },
  { 
    path: 'car/details/:id', 
    component: CadDetailsComponent 
  },
  { 
    path: 'car/details/:id/platforms-products', 
    component: CarProductsComponent 
  }
];

이거면 되겠네요.이 방법으로 라우터는 Option ID 파라미터를 기반으로 다음 루트를 파악합니다.

어떤 컴포넌트에서 다른 컴포넌트로 루트를 경유하여 루트 파라미터를 송신하는 방법에는 3가지가 있습니다.그러나 먼저 관련 컴포넌트 .ts 파일에 이러한 라이브러리를 Import하고 컨스트럭터에서 정의합니다.

private route: ActivatedRoute
private router: Router

첫 번째 방법: 필요한 라우팅 파라미터

//Route Configuration
{path: 'user/:id', component: UserDetailComponent}

//Set Hyperlink/routerLink
<a [routerLink]="['/user', user.id]"></a> 

 //Requesting Url after click on hyperlink
 http://localhost:4200/user/6

//Now you can read id value in navigated component
this.route.snapshot.paramMap.get('id');

두 번째 방법: 옵션 경로 파라미터

//Route Configuration
    {path: 'user', component: UserDetailComponent}
    
    //Set Hyperlink/routerLink
    <a [routerLink]=['/user', {name: userName, status: true}]"></a>


//Requesting Url after click on hyperlink
    http://localhost:4200/user;name:userNameValue;status:true

//Now you can read values in navigated component
    this.route.snapshot.paramMap.get('userId');
    this.route.snapshot.paramMap.get('userName');

서드웨이: 옵션 패스 파라미터

//Route Configuration
    {path: 'user', component: UserDetailComponent}
    
    //Set Hyperlink/routerLink
    <a [routerLink]="['/user']"  [queryParms]="{userId:'911', status:true}"></a>

    //Requesting Url after click on hyperlink
    http://localhost:4200/user?userId=911&status=true

    
    //Now you can read values in navigated component
    this.route.snapshot.paramMap.get('userId');
    this.route.snapshot.paramMap.get('userName');

참고 자료: https://qastack.mx/programming/44864303/send-data-through-routing-paths-in-angular

Angular 8에서는 라우터 설정을 변경하지 않고 단순히 파라미터를 추가할 수 있습니다.

Angular Doc 옵션 매개 변수

module.routing.module.ts로 지정합니다.

const routes: Routes = [
  { path: 'somePath/:RequiredParam', component: Yourcomponent }
];

템플릿:

<div [RouterLink] = ['somePath', requiredParamValue, {optionalParam: value}]></div>

이 문제의 다른 예와 마주쳤고, 이에 대한 해결책을 찾는 중에 여기에 왔습니다.문제는 제가 아이들을 위해 작업하는 것과 부품을 천천히 로드하는 것 뿐 아니라 작업을 최적화해야 한다는 것이었습니다.즉, 부모 모듈의 로드가 늦어지는 경우입니다.주요 사항은 경로에서 '/:id'를 사용했는데, '/'이(가) 포함된 것에 대한 불만입니다.여기 정확한 문제는 아니지만, 적용되죠.

부모로부터의 앱 라우팅

...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'pathOne',
        loadChildren: 'app/views/$MODULE_PATH.module#PathOneModule'
      },
      {
        path: 'pathTwo',
        loadChildren: 'app/views/$MODULE_PATH.module#PathTwoModule'
      },
...

하위 경로 지연 로드

...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: OverviewComponent
      },
      {
        path: ':id',
        component: DetailedComponent
      },
    ]
  }
];
...

이 매처 기능을 사용하면 컴포넌트를 다시 렌더링하지 않고도 원하는 동작을 할 수 있습니다.url.length가 0인 경우 옵션 파라미터는 없으며 url.length는 1입니다.옵션 파라미터는 1개입니다.id - 옵션 파라미터 이름입니다.

  const routes: Routes = [
  {
    matcher: (segments) => {
      if (segments.length <= 1) {
        return {
          consumed: segments,
          posParams: {
            id: new UrlSegment(segments[0]?.path || '', {}),
          },
        };
      }
      return null;
    },
    pathMatch: 'prefix',
    component: UserComponent,
  }]

마스터 상세 뷰에서도 같은 문제가 발생.마스터 뷰는 :elementId 파라미터 없이 표시할 수 있지만 상세선택이 열려 있고 URL에 :elementId가 표시되어 있어야 합니다.

다음과 같이 해결했습니다.

const routes: Routes = [
  {
    path: '',
    component: MasterDetailComponent,
    children: [
      {
        path: ':elementId',
        children: [
          {
            path: 'details',
            component: DetailComponent
          },
          {
            path: '',
            redirectTo: 'details'
          }
        ]
      }
    ]
  }
];

다음으로 MasterDetailComponent(ngOnInit 메서드 등)에서 자경로를 사용하여 :elementId를 얻을 수 있습니다.

const childRouteWithElementId = this.route.snapshot.children[0];
const elementIdFromUrl = childRouteWithElementId.params.elementId;
if (!!elementIdFromUrl ) {
  // Do what you need to with the optional parameter
}

물론 자녀 루트 없이 동일한 작업을 수행할 수 있으며 URL 끝에는 옵션의 elementId만 있습니다.

코멘트는 할 수 없습니다만, Angular 2 옵션 루트 파라미터에 대해서

Angular 6 업데이트:

import {map} from "rxjs/operators"

constructor(route: ActivatedRoute) {
  let paramId = route.params.pipe(map(p => p.id));

  if (paramId) {
    ...
  }
}

Angular6 라우팅의 상세한 것에 대하여는, https://angular.io/api/router/ActivatedRoute 를 참조해 주세요.

로딩이 느릴 때와 같은 문제에 직면하여 이 작업을 수행했습니다.

const routes: Routes = [
  {
    path: 'users',
    redirectTo: 'users/',
    pathMatch: 'full'
  },
  {
    path: 'users',
    loadChildren: './users/users.module#UserssModule',
    runGuardsAndResolvers: 'always'
  },
[...]

다음으로 컴포넌트:

  ngOnInit() {
    this.activatedRoute.paramMap.pipe(
      switchMap(
        (params: ParamMap) => {
          let id: string = params.get('id');
          if (id == "") {
            return of(undefined);
          }
          return this.usersService.getUser(Number(params.get('id')));
        }
      )
    ).subscribe(user => this.selectedUser = user);
  }

이쪽:

  • 「」가 없는 /가 있는 루트로 리다이렉트 됩니다.그유 the the because because 。pathMatch: 'full'이러한 특정 풀루트만 리다이렉트 됩니다.

  • ㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇ는,users/:id수신되었습니다.가 「」인 .users/,id- 아, 아, 아! - 아, 아, 아!""ngOnInit 그에 그렇지 않으면, 「」, 「」, 「」, 「」, 「」, 「」, 「」.idid 입니다.

  • 구성 는 에 합니다.selectedUserngIf(*ngIf)입니다.

언급URL : https://stackoverflow.com/questions/34208745/angular-2-optional-route-parameter

반응형