简体   繁体   English

如何在角度4的嵌套路线中存储路线参数?

[英]how to storing route params in nested routes in angular 4?

reason of using nested route for me is handling dynamically icon and back button for every page.i have abstract route because when i click to back button route params disappear and i put an abstract path to keep id and questionnaire type parameter in url.my abstract path is Questionaire. 我使用嵌套路由的原因是动态处理每个页面的图标和后退按钮。我具有抽象路由,因为当我单击后退按钮时,路由参数消失了,我在url.my中放置了抽象路径以保留id和问卷类型参数路径是问卷。

      const routes: Routes = [
          {
             path: '',
              component: LayoutComponent, 
            children:[
              { path: 'Home', component: HomeComponent,data:{icon:'fa-home'} },
              { path: 'QuestionaireList', component: QuestionaireListComponent,data:{icon:'fa-list-ul',previousState:'/Home'} },
              { path: 'ModifyMetaContent/:metaContentId/:title', component: ModifyMetaContentComponent,data:{icon:'fa-database',previousState:'/MetaContentList'}}

              { 
                path: 'Questionaire/:id',
                children:[
                { path: 'MetaContentList', component: MetaContentListComponent,data:{icon:'fa-database',previousState:'/QuestionaireList'}}

      ]},




              { 
                path: 'Questionaire/:questionnaireType',
              children:
              [     
                 { path: 'AddQuestionnaire', component: CreateQuestionnaireComponent,data:{icon:'fa-plus',previousState:'/QuestionaireList'}},      
              ]},
              { 
              path: 'Questionaire/:questionnaireType/:id',
              children:[ 
              { path: 'UpdateQuestionnaire', component: EditComponent,data:{icon:'fa-pencil',previousState:'/QuestionaireList'}  },
              { path: 'QuestionList', component: QuestionListComponent,data:{icon:'fa-pencil',previousState:'/QuestionaireList'} },
              { path: 'ImportQuestion',    component: ImportQuestionComponent,data:{icon:'fa-plus',previousState:'/QuestionaireList'}   },

            ]} ,
            ]},
      ];

MetaContentList.Component.html MetaContentList.Component.html

   <a class="ui labeled positive icon small button" [routerLink]="['/ModifyMetaContent','',questionnaireTitle]">
  <i class="plus icon"></i>
 new metaContent
</a>

i store previous url in snapshot.data.previousState but when i click to ModifyMetaContent i go to 我将先前的URL存储在snapshot.data.previousState但是当我单击ModifyMetaContent我转到

localhost:4200/ModifyMetaContent/... 本地主机:4200 / ModifyMetaContent / ...

and when i click to back button , id and questionnairetype disappear from url.when i to click to ModifyMetaContent i expected go to : 当我单击返回按钮时, idquestionnairetype将从url中消失。当我单击以单击ModifyMetaContent时,我希望转到:

localhost:4200/Questionaire/b8b55b42-f39f-4359-93d0-0260ddf3827f/MetaContentList/ModifyMetaContent/... 本地主机:4200 /问卷/ b8b55b42-f39f-4359-93d0-0260ddf3827f / MetaContentList / ModifyMetaContent / ...

and when i click to back button i expected go to 当我单击返回按钮时,我希望转到

.../Questionaire/b8b55b42-f39f-4359-93d0-0260ddf3827f/MetaContentList/ but url set to localhost:4200/MetaContentList ... / Questionaire / b8b55b42-f39f-4359-93d0-0260ddf3827f / MetaContentList /但网址设置为localhost:4200 / MetaContentList

and this error occurred : 并发生此错误:

Cannot match any routes. 无法匹配任何路线。 URL Segment: 'MetaContentList' 网址段:“ MetaContentList”

i handle this case by nested states of angularjs ui-router.is any solution to this issue in angular2+ router ? 我通过angularjs ui-router的嵌套状态处理这种情况.angular2 +路由器中的这个问题有解决方案吗?

{ path: '', redirectTo: 'main', pathMatch: 'full' 
},
{ path: 'header', component: HeaderComponent},
{ path: 'login', component: LoginComponent},
{ path: 'logout', component: LogoutComponent},
{ path: 'register', component: RegisterComponent},
 { path: 'profile', children: [

    { path: ':id', component: ProfileComponent,children: [
    { path: 'profileform/:id',  component: ProfileformComponent,outlet: 'formOutlet', pathMatch: 'full' }]}]},


 { path: 'main', component: MainComponent, children: [
    { path: 'stone/:id',  component: StoneComponent,outlet: 'aux', children: [
    { path: 'steemblog', component: BlogComponent,outlet: 'blogoutlet'},
    {path: 'extlogin', component: ExternalLoginComponent, outlet:'blogoutlet'
    }]}]},

{ path: '**', component: NotfoundComponent} {路径:“ **”,组件:NotfoundComponent}

       this.router.navigate(['/main',{outlets: { 'aux' : ['stone',this.state, {outlets: { 'blogoutlet' : ['steemblog',
        { 'access_token': this.accessToken, 'expires_in': this.expiresIn, 
      'userName':this.userName }]}}]}}]);

      }

Hi I am using outlets as well, but if you think those away you might be able to get yours to work? 嗨,我也正在使用网点,但是如果您认为那些网点不在,您也许可以使您的网点开始工作吗? Not sure if this is exactly what you want but perhaps it helps. 不知道这是否正是您想要的,但也许有帮助。

i solve this issue by change route structure and add a function for previousstate link in appcomponent: 我通过更改路由结构解决了这个问题,并在appcomponent中为previousstate链接添加了一个功能:

my router: 我的路由器:

    const routes: Routes = [
      {
         path: '',
          component: LayoutComponent, 
            children:[
          { path: 'Home', component: HomeComponent,data:{icon:'fa-home',previousState:[]} },
          { path: 'QuestionaireList', component: QuestionaireListComponent,data:{icon:'fa-list-ul',previousState:['/Home']} },

          { path: 'Questionaire/:id',children:[
            { path: 'MetaContentList', component: MetaContentListComponent,data:{icon:'fa-database',previousState:['/QuestionaireList']}},
            { path: 'ModifyMetaContent/:metaContentId/:title', component: ModifyMetaContentComponent,data:{icon:'fa-database',previousState:['Questionaire','MetaContentList']}}
            ]},
          { path: 'Questionaire/:questionnaireType',
            children:[{ path: 'AddQuestionnaire', component: CreateQuestionnaireComponent,data:{icon:'fa-plus',previousState:['/QuestionaireList']}}]},
          {path: 'Questionaire/:questionnaireType/:id',
            children:[ 
          { path: 'UpdateQuestionnaire', component: EditComponent,data:{icon:'fa-pencil',previousState:['/QuestionaireList']}  },
          { path: 'QuestionList', component: QuestionListComponent,data:{icon:'fa-pencil',previousState:['/QuestionaireList']} },
          { path: 'ImportQuestion',    component: ImportQuestionComponent,data:{icon:'fa-upload',previousState:['/QuestionaireList']}   },
        ]} ,
        ]},      
  ];

in my router 2 state is possible : 在我的路由器2状态下是可能的:

  1. previous url is normal 以前的网址是正常的
  2. previous url is nested url for implementation above state i put previousstate in an array if we are at state 2 array.length is bigger than 1 .for embedding route params i create a method in appcomponent: 以前的url是嵌套的url,用于在状态以上实现的实现,如果我们处于状态2 array.length大于1,则将previousstate放入数组中。为了嵌入路由参数,我在appcomponent中创建了一个方法:

method for get lastchild : 获取lastchild的方法:

 getSnapshot(route: ActivatedRoute){
                let lastChild = route;
                while (lastChild.firstChild) {
                lastChild = lastChild.firstChild;
                }
                return lastChild;
                } 

method for get previous state : 获取先前状态的方法:

getPreviousUrl(a):string{
  let previousState:string;
  const previousStateLength=a.snapshot.data.previousState ? a.snapshot.data.previousState.length :null;
  if(previousStateLength!==null){
   if(previousStateLength<=1 )
   {previousState=a.snapshot.data.previousState[0];}
   else{
     previousState='/';
     let parentParams=[''];
     let j:number=0;
     let b=a;
     while(b.parent){
       b.parent.params.subscribe((params)=>{
         Object.keys(params).map(key=>parentParams[j]+=params[key]+'/');
         for(let i=0;i<previousStateLength-1;i++){
           if(parentParams[j]!==undefined)
           previousState+=a.snapshot.data.previousState[i]+'/'+parentParams[j];
         }
        })
       b=b.parent;
     j++;
     }
     previousState+=a.snapshot.data.previousState[previousStateLength-1];

   }
   return previousState;
  }

}

and get data : 并获取数据:

constructor(router:Router,route:ActivatedRoute) {

     router.events
     .filter(event => event instanceof NavigationEnd)

     .subscribe(e => {

       const lastChild=this.getSnapshot(route);
       this.routerIcon = lastChild.snapshot.data.icon;
       this.previousState=this.getPreviousUrl(lastChild);

   });

its work for me bu i want to maximality improve it. 我想尽最大努力改善它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM