2017-08-07 12 views
12

Tôi đã cấu hình tuyến đường sau:Restrict tuyến sử dụng tùy chỉnh khớp

const routes: Routes = [ 
    { 
    component: MyComponent, 
    path: '', 
    children: [ 
     { 
     component: MyListComponent, 
     path: '' 
     }, 
     { 
     component: MyFormComponent, 
     path: ':id/edit' 
     }, 
     { path: '**', redirectTo: '' } 
    ] 
    } 
]; 

Để hạn chế các thông số như số, tôi bắt đầu để tìm kiếm và sau khi dành toooooooooo nhiều thời gian, tôi đã tìm thấy một cách thức này đóng (tôi không biết tại sao) phát hành: https://github.com/angular/angular/issues/12442

Vì vậy, tôi đã thay đổi cấu hình của tôi (especifically phần mà vấn đề) như sau:

{ 
    component: MyFormComponent, 
    matcher: ComplexUrlMatcher('id', /[1-9]+\/edit/) 
} 

export function ComplexUrlMatcher(paramName: string, regex: RegExp) { 
    return (
     segments: UrlSegment[], 
     segmentGroup: UrlSegmentGroup, 
     route: Route) => { 

     const parts = [regex]; 
     const posParams: { [key: string]: UrlSegment } = {}; 
     const consumed: UrlSegment[] = []; 

     let currentIndex = 0; 

     for (let i = 0; i < parts.length; ++i) { 
      if (currentIndex >= segments.length) { 
       return null; 
      } 
      const current = segments[currentIndex]; 

      const part = parts[i]; 
      if (!part.test(current.path)) { 
       return null; 
      } 

      posParams[paramName] = current; 
      consumed.push(current); 
      currentIndex++; 
     } 

     if (route.pathMatch === 'full' && 
      (segmentGroup.hasChildren() || currentIndex < segments.length)) { 
      return null; 
     } 

     return { consumed, posParams }; 
    } 
} 

Nguồn: https://gist.github.com/matanshukry/22fae5dba9c307baf0f364a9c9f7c115


Nó gần như hoạt động. Nếu tôi đi đến một con đường như thế này:

my_path/1 

... nó hoạt động, nhưng những gì tôi muốn là:

my_path/1/edit 

Làm thế nào tôi có thể sửa chữa chức năng này để làm cho nó hoạt động?

Trả lời

2

Bạn sẽ cần phải tiếp tục lồng ghép các thành phần con trong bộ định tuyến của mình để làm cho chức năng này hoạt động ngoài hộp. Các công trình cho tôi với phiên bản bộ định tuyến 4 sau đây và nó sẽ chỉ cho phép các thông số id là một hoặc nhiều số và tham số hành động để phù hợp với từ khóa tìm kiếm "chỉnh sửa":

const routes: Routes = [ 
    { 
     component: MyComponent, 
     path: '', 
     children: [ 
     { 
      component: MyListComponent, 
      path: '' 
     }, 
     { 
      matcher: ComplexUrlMatcher("id", /[0-9]+/), 
      component: MyFormComponent, 
      { 
       matcher: ComplexUrlMatcher("action", /(edit)/), 
       component: MyFormEditComponent, 
      } 
     }, 
     { path: '**', redirectTo: '' } 
     ] 
    } 
]; 

Nếu sử dụng thành phần con không làm việc cho bạn, bạn sẽ phải viết lại một số logic regex để phù hợp với nhu cầu của bạn.

Các vấn đề liên quan